2

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.

Community
  • 1
  • 1
user1527227
  • 2,068
  • 5
  • 25
  • 36

2 Answers2

7

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.

RocketDonkey
  • 36,383
  • 7
  • 80
  • 84
  • @user1527227 No problem at all, happy to help! I would suggest practicing list comprehensions until they start to 'click' - they are one of those features that you start to get a handle on and then you wonder how you could live without them :) – RocketDonkey Nov 20 '12 at 19:26
  • One of the best explanations of this I've found. – SuperFamousGuy Mar 22 '13 at 16:28
0
indices = []
for idx, elem in enumerate(my_list):
    if elem=='whatever':
        indices.append(idx)
volcano
  • 3,578
  • 21
  • 28