Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python get index of first element of list that matches condition

# Find first index (or value) that meets condition
my_list = [2, 4, 6, 9, 10]

# Option 1. Use an iterator (does not scan all list)
y = (i for i,x in enumerate(my_list) if is_odd(x))
idx1 = next(y)  # <== index of first element

y = (x for i,x in enumerate(my_list) if is_odd(x))
v1 = next(y)  # <== value of first element


# Option 2. Use a list comprehension (scans all list)
idx1 = [i for i,x in enumerate(my_list) if x % 2 != 0][0]
v1 = [x for i,x in enumerate(my_list) if x % 2 != 0][0]
 
PREVIOUS NEXT
Tagged: #python #index #element #list #matches #condition
ADD COMMENT
Topic
Name
6+8 =