Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding indexes of even numbers in a list

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?

like image 204
Xyzzel Avatar asked Dec 05 '25 14:12

Xyzzel


2 Answers

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]
like image 186
shad0w_wa1k3r Avatar answered Dec 08 '25 02:12

shad0w_wa1k3r


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))
like image 36
Kapil Avatar answered Dec 08 '25 04:12

Kapil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!