Reputation: 2238
I read the post: How to find all occurrences of an element in a list? How to find all occurrences of an element in a list?
The answer given was:
indices = [i for i, x in enumerate(my_list) if x == "whatever"]
I know this is list comprehension but I cannot break this code down and understand it. Can someone please piece meal it for me?
If do the following code:I know enumerate will just create a tuple:
l=['a','b','c','d']
enumerate(l)
output:
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
If there's a simpler way I'd be open to that too.
Upvotes: 2
Views: 16806
Reputation: 37249
indices = [i for i, x in enumerate(my_list) if x == "whatever"]
is equivalent to:
# Create an empty list
indices = []
# Step through your target list, pulling out the tuples you mention above
for index, value in enumerate(my_list):
# If the current value matches something, append the index to the list
if value == 'whatever':
indices.append(index)
The resulting list contains the index positions of each match. Taking that same for
construct, you can actually go deeper and iterate through lists-of-lists, sending you into an Inception-esque spiral of madness:
In [1]: my_list = [['one', 'two'], ['three', 'four', 'two']]
In [2]: l = [item for inner_list in my_list for item in inner_list if item == 'two']
In [3]: l
Out[3]: ['two', 'two']
Which is equivalent to:
l = []
for inner_list in my_list:
for item in inner_list:
if item == 'two':
l.append(item)
The list comprehension you include at the beginning is the most Pythonic way I can think of to accomplish what you want.
Upvotes: 7
Reputation: 3582
indices = []
for idx, elem in enumerate(my_list):
if elem=='whatever':
indices.append(idx)
Upvotes: 0