Ads by ProfitSence
Close

Python find item in list

Last Updated on Wednesday 5th Oct 2022

python where in list

Checking if something is inside

Checking whether something is inside a list or not.You can use the in operator.

			
					3 in [1, 2, 3] # => True

			
	

python find in list

Filtering a collection

Finding all elements in a sequence that meet a certain condition. You can use list comprehension or generator expressions for that

			
					matches = [x for x in lst if fulfills_some_condition(x)]
matches = (x for x in lst if x > 6)

			
	

Finding the location of an item

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

			
	

python list find

if you have duplicates, .index always returns the lowest index

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

			
	

python search list

Finding the first occurrence

If you only want the first thing that matches a condition (but you don't know what it is yet), it's fine to use a for loop

			
					next(x for x in lst if ...)
next((x for x in lst if ...), [default value])

			
	

If there are duplicates and you want all the indexes then you can use enumerate()

			
					[i for i,x in enumerate([1,2,3,2]) if x==2] # => [1, 3]

			
	

python find item in list