Python Forum
list comprehension error - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: list comprehension error (/thread-6060.html)



list comprehension error - atux_null - Nov-04-2017


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?


RE: list comprehension error - buran - Nov-04-2017

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?


RE: list comprehension error - atux_null - Nov-04-2017

sorry, typo. i need to have [10,0,10,10]


RE: list comprehension error - buran - Nov-04-2017

what is the logic? because without underlying logic here it is:
mylist = [10, 0, 10, 10]



RE: list comprehension error - atux_null - Nov-04-2017

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]


RE: list comprehension error - buran - Nov-04-2017

againĀ  what is the logic -how you decide 10 or 0?


RE: list comprehension error - wavic - Nov-04-2017

10 if the number is odd else 1?


RE: list comprehension error - atux_null - Nov-04-2017

the code
10 if the number is odd else 1
? returns [10,1,10,1]


RE: list comprehension error - Mekire - Nov-05-2017

(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.