if/else condition in a list comprehension | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

if/else condition in a list comprehension

I am trying to do an if/else with a list comprehension (I think). I tried to follow a normal if conditional format with the if/else at the end. I tried to add 'num for num in nums'. A few other things like the commented code at the bottom...but the best I can do is make res[] a list of 'None's. I'm sure this will never be crucial and a normal if/else in a for loop works, it's just that I read Trey Hunner's visual take on List Comps and wondered about an else. nums = [2,53,4,7,11,1] print(nums) res = [] for num in nums: if num <= 7: res.append("less") else: res.append("more") print(res) nums = [2,53,4,7,11,1] print(nums) res = [] res = [res.append("less") if num <= 7 else res.append("more") for num in nums ] print(res) # [a if tC else b for i in items if fC] # [item # for sublist in myList # for item in (sublist if type(sublist) is list else sublist['val']) #] python-3.x

30th Nov 2019, 6:59 AM
James
James - avatar
7 Answers
+ 3
Yes, Thank You Jan! I don't know why I was appending. I appreciate your quick answer.
30th Nov 2019, 7:18 AM
James
James - avatar
+ 3
If you do this, the output will be correct: nums = [2,53,4,7,11,1] print(nums) res = [] [res.append("less") if num <= 7 else res.append("more") for num in nums] print(res) # or do it this way: nums = [2,53,4,7,11,1] print(nums) res = ["less" if num <= 7 else "more" for num in nums] print(res) # output is: [2, 53, 4, 7, 11, 1] ['less', 'more', 'less', 'less', 'more', 'less']
30th Nov 2019, 11:50 AM
Lothar
Lothar - avatar
+ 3
If you want to read up on comprehension details: https://code.sololearn.com/ck6HicJ6Z8jG/?ref=app
30th Nov 2019, 12:00 PM
HonFu
HonFu - avatar
+ 1
i see Lothar. i could append inside the comprehension if i didnt assign it outside. thank you for that.
30th Nov 2019, 12:37 PM
James
James - avatar
+ 1
عاوزه استفسار عن حاجه
1st Dec 2019, 8:40 AM
Hager Gamal
Hager Gamal - avatar
0
اعا
30th Nov 2019, 4:51 PM
ندوة الضاهر
ندوة الضاهر - avatar
0
تنوت
30th Nov 2019, 4:51 PM
ندوة الضاهر
ندوة الضاهر - avatar