Home > Back-end >  How To Find Elements In a List
How To Find Elements In a List

Time:07-20

I need to extract items from a List as shown in the working example below.

I would like to avoid adding an additional

or ('blah-blah' in data)

for every instance I want to find.
Instead, i would like to shorten and simply this process to something like apple, berry, blah-blah as a single entry.

my_data = ['apple', 'orange', 'banana', 'strawberry', 'peach']
print(type(my_data))

all_instances = []

for data in my_data:
    if ('apple' in data) or ('berry' in data):
        all_instances.append(data)
print('All Instances Found:', all_instances)

Thank you in advance.

CodePudding user response:

If you want to have simple code, you can put all your desired input into a list and do list comparison.

my_data = ['apple', 'orange', 'banana', 'strawberry', 'peach']

input_ = ['apple','berry']

result = [i for i in my_data for j in input_ if j in i]
Out[436]: ['apple', 'strawberry']
  • Related