0
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 ?

TSR
  • 17,242
  • 27
  • 93
  • 197

1 Answers1

0

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)):
    ...
CryptoFool
  • 21,719
  • 5
  • 26
  • 44