Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If statement in list dynamic creation

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)):
    ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading