0

I'm using a PYNQ board and i following some tutorials. In one of them they are using a for loop, but i dont understand well the syntax:

leds = [base.leds[index]) for index in range(MAX_LEDS)]

I mean, Why is one parenthesis? is a special syntax?

mkrieger1
  • 10,793
  • 4
  • 39
  • 47
  • 1
    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) – mkrieger1 Apr 18 '20 at 19:45

1 Answers1

2

This is called a list comprehension.

List comprehensions are a special kind of expression in Python. List comprehensions return, well, a list. They are mainly meant to replace simple list-building code which would otherwise require a traditional for loop.

For example, the following loop:

leds = []
for index in range(MAX_LEDS):
    leds.append(base.leds[index])

Can be rewritten as the list comprehension you have shown:

leds = [base.leds[index] for index in range(MAX_LEDS)]

List comprehensions also allow filtering on the items. So for example, the above loop can be further expanded to:

leds = []
for index in range(MAX_LEDS):
    if 'green' in base.lends[index]:
        leds.append(base.leds[index])

and can be converted to the following list comprehension:

leds = [base.leds[index] for index in range(MAX_LEDS) if 'green' in base.leds[index]]

Please read about the exact syntax online.

Aviv Cohn
  • 11,431
  • 20
  • 52
  • 95