0

When I was searching how to find the index of items in a list, the answer included some code that I couldn't figure out.

Specifically this:

[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'bar']

I understood most of it but the 'i for i' segment has left me confused. I am very familiar with normal for loops but I do not understand this, can someone please explain?

Dale K
  • 16,372
  • 12
  • 37
  • 62
  • 2
    See https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it – Mitchell Olislagers Feb 01 '21 at 02:09
  • 2
    Does this answer your question? [What does "list comprehension" mean? How does it work and how can I use it?](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it) – buddemat Feb 01 '21 at 10:44

1 Answers1

1

I like to break list comprehensions up into normal for loops to help me understand what they're doing (or in troubleshooting one of my own).

output = [i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'bar']

is the same as:

output = []
for i, j in enumerate(['foo', 'bar', 'baz']):
    if j == 'bar':
        output.append(i)

List comprehensions, especially large ones, run faster than a traditional for loop.

goalie1998
  • 1,283
  • 1
  • 8
  • 14