I want to find the indexes of the even numbers in this list.
messy = [5, 2, 8, 1, 3]
y = [x for x in messy if x%2==0]
f = y[0]
g = y[1]
print(f, g)
>>> 2 8
z = messy.index(f)
zz = messy.index(g)
print(z)
>>> 1
print(y) outputs [2, 8] and that isn't in the list, and that's why I can't messy.index(y)
I'm a bit confused here. Any help?
The .index method will fail when there are 2 or more of the same value elements in your list. Instead, you can simplify by enumerating your list and using the indices as follows
even_indices = [i for i, elem in enumerate(messy)
if elem % 2 == 0]
You can use functional approach using filter function and lambda expression:
For python 2.x:
filter(lambda a:a%2==0, messy)
For python 3.x:
list(filter(lambda a:a%2==0, messy))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With