If statement in list dynamic creation

Question:

colors = [ (i % 2 == 0)? "W" else "B" for i in range(4000)]

The above is an invalid python syntax. But you get the goal, colors should be ["W", "B", "W",…] 4000 times.

If there a way to achieve this in a single line in python ?

Asked By: TSR

||

Answers:

You were close. You just didn’t have the syntax quite right. Here’s what you want:

colors = [ "W" if (i % 2 == 0) else "B" for i in range(4000)]

Result:

['W', 'B', 'W', 'B', 'W', 'B', 'W', 'B' ....

If you are going to iterate over the colors rather than really needing them all at once in an in-memory list, using a generator is better for both speed and memory consumption…

for color in ("W" if (i % 2 == 0) else "B" for i in range(20)):
    ...
Answered By: CryptoFool
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.