sage
0
Q:

python find in list

# There is several possible ways if "finding" things in lists.
'Checking if something is inside'
3 in [1, 2, 3] # => True
'Filtering a collection'
matches = [x for x in lst if fulfills_some_condition(x)]
matches = filter(fulfills_some_condition, lst)
matches = (x for x in lst if x > 6)
'Finding the first occurrence'
next(x for x in lst if ...)
next((x for x in lst if ...), [default value])
'Finding the location of an item'
[1,2,3].index(2) # => 1
[1,2,3,2].index(2) # => 1
[1,2,3].index(4) # => ValueError
[i for i,x in enumerate([1,2,3,2]) if x==2] # => [1, 3]
11
list.index(element)
13
# app.py

streaming = ['netflix', 'hulu', 'disney+', 'appletv+']

index = streaming.index('disney+')
print('The index of disney+ is:', index)
6
# Python code to demonstrate 
# finding whether element 
# exists in listof list 
  
# initialising nested lists 
ini_list = [[1, 2, 5, 10, 7], 
            [4, 3, 4, 3, 21], 
            [45, 65, 8, 8, 9, 9]] 
  
elem_to_find = 8
elem_to_find1 = 0
  
# element exists in listof listor not? 
res1 = any(elem_to_find in sublist for sublist in ini_list) 
res2 = any(elem_to_find1 in sublist for sublist in ini_list) 
  
# printing result 
print(str(res1), "\n", str(res2)) 
0
'''    
    check if list1 contains all elements in list2
'''
result =  all(elem in list1  for elem in list2)
if result:
    print("Yes, list1 contains all elements in list2")    
else :
    print("No, list1 does not contains all elements in list2"
-1

New to Communities?

Join the community