python list search for element

linkaiyi
Follow

use index to search for first occurrance of one element

list.index(element), list.index(element, start, end) element can be found from start position or start and end position can be given

list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
element = 7
list_numbers.index(element)
list_numbers.index(element, 1, 5)

enumerate the list

list_numbers = [3, 1, 2, 3, 3, 4, 5, 6, 3, 7, 8, 9, 10]
[i for i, n in enumerate(list_numbers) if n == 3] # List comprehension

list_numbers = [3, 1, 2, 3, 3, 4, 5, 6, 3, 7, 8, 9, 10]
g = (i for i, n in enumerate(list_numbers) if n == 3) # Generator expression
print("Generators store values, the first value here is:", next(g), ". Then the next is:", next(g), "followed by ", next(g),"and finally ", next(g))
Object has 0 attachments

Was this article helpful?

This article is viewed 14 times!

0 Comments

Leave a Comment

Support