Python For loop different syntax

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?

Upvotes: 0

Views: 65

Answers (1)

Aviv Cohn
Aviv Cohn

Reputation: 17243

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.

Upvotes: 2

Related Questions