Jake Rayner
Jake Rayner

Reputation: 32

Searching all types of an item in a list

Hi im a student learning python and I need some help with a question below. Thanks for helping.

I want to find all the types of an item in a list when searching an item.

Eg:

list = ["milk_skim", "milk_fat", "milk_lowfat", "juice", "water"]

def do_fuction():
print(all_items_in_list_with_milk)

item_searched_for = milk
if item_searched_for in list:
do_fuction()

I want the output to be all the types of milk. So far I need the user to perfectly write the type of milk as the input (item_searched_for) and then I only get searched item not all of the types as I want.

Upvotes: 0

Views: 59

Answers (4)

Johnny John Boy
Johnny John Boy

Reputation: 3283

Really simple, just use in per item in your shopping list:

list = ["milk_skim", "milk_fat", "milk_lowfat", "juice", "water"]

item_searched_for = 'milk'

for item in list:
    if item_searched_for in item:
        print(item)

Just thought, you shouldn't use

list

so here is an updated bit of code with a function:

shopping_list = ["milk_skim", "milk_fat", "milk_lowfat", "juice", "water"]

def my_shopping_list(item, shopping_list):
    for product in shopping_list:
        if item in product:
            print(product)

my_shopping_list("milk", shopping_list)

Per your comment to save later:

shopping_list = ["milk_skim", "milk_fat", "milk_lowfat", "juice", "water"]

def my_shopping_list(item, shopping_list):
    new_shopping_list = []
    for product in shopping_list:
        if item in product:
            print(product)
            new_shopping_list.append(product)
    return new_shopping_list

my_variable = my_shopping_list("milk", shopping_list)
print(my_variable)

milk_skim
milk_fat
milk_lowfat
['milk_skim', 'milk_fat', 'milk_lowfat']

Upvotes: 0

list = ["milk_skim", "milk_fat", "milk_lowfat", "juice", "water"]

def do_function(): matchedStrings = [string for string in list if "milk" in string] print(matchedStrings) do_function()

Upvotes: 0

Mert
Mert

Reputation: 71

This should work

def function(): 
    for name in list:
        if 'milk' in name:
            print(name)
    

Upvotes: 0

Óscar López
Óscar López

Reputation: 236112

You can filter the list using list comprehensions:

drink_list = ["milk_skim", "milk_fat", "milk_lowfat", "juice", "water"]
[drink for drink in drink_list if 'milk' in drink]

Upvotes: 1

Related Questions