python find value in list code example

Example 1: get index of list python

list.index(element)

Example 2: 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]

Example 3: identify list elements python

# app.py

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

index = streaming.index('disney+')
print('The index of disney+ is:', index)

Example 4: python find item in list

>>> ["foo", "bar", "baz"].index("bar")
1

Example 5: how to find index of list of list in python

[(i, colour.index(c))
 for i, colour in enumerate(colours)
 if c in colour]

Example 6: python search list by value

[1,2,3].index(2) # => 1
[1,2,3].index(4) # => ValueError