Python Forum

Full Version: list comprehension error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

hi. i am looking to create a list [10,0,10,0]. up to now i have the following code:
mylist=[10 if i%2==1 else 0 for i in range(1,5)]
the above returns [10,0,10,0]. Any ideas on how to fix that please?
Your goal
(Nov-04-2017, 06:03 PM)atux_null Wrote: [ -> ]i am looking to create a list [10,0,10,0]

the output of your script:
(Nov-04-2017, 06:03 PM)atux_null Wrote: [ -> ]the above returns [10,0,10,0]

what is the problem?
sorry, typo. i need to have [10,0,10,10]
what is the logic? because without underlying logic here it is:
mylist = [10, 0, 10, 10]
the logic is to have in the format:
mylist=[___for i in range(1,5)]
where ___ needs to get substituted from the necessary part of the code to make the list have [10,0,10,10]
againĀ  what is the logic -how you decide 10 or 0?
10 if the number is odd else 1?
the code
10 if the number is odd else 1
? returns [10,1,10,1]
(Nov-04-2017, 08:03 PM)atux_null Wrote: [ -> ]the logic is to have in the format:
mylist=[___for i in range(1,5)]
where ___ needs to get substituted from the necessary part of the code to make the list have [10,0,10,10]
Well, I mean:
>>> [0 if i == 2 else 10 for i in range(1,5)]
[10, 0, 10, 10]
>>>
Seems to get what you want, but I've got to say that is a really stupid problem.