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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.