if/else condition in a list comprehension | SoloLearn: Learn to code for FREE!

+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

11/30/2019 6:59:48 AM

James

9 Answers

New Answer

+4

I don't exactly understand the question in complete, but you can do your code within an oneliner with list comprehension like print(['less' if x <= 7 else 'more' for x in nums])

+3

Yes, Thank You Jan! I don't know why I was appending. I appreciate your quick answer.

+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']

+3

If you want to read up on comprehension details: https://code.sololearn.com/ck6HicJ6Z8jG/?ref=app

+2

+1

i see Lothar. i could append inside the comprehension if i didnt assign it outside. thank you for that.

+1

عاوزه استفسار عن حاجه

0

0