Is there a way to do nested list comprehension?

for example I can square a range of numbers, even only.

[x*x for x in range(1,20) if x % 2==0]

but what if I want to square the even and times the odd by 3.

[x*x for x in range(1,20) if x % 2==0 else x * 3]

, unfortunately that errors. How do I do it?

Recommended Answers

Yes you can nest, but your request does not take one, only conditional expression in value part:

[x*x if x % 2==0 else x * 3 for x in range(1,20)]
Jump to Post

All 4 Replies

Yes you can nest, but your request does not take one, only conditional expression in value part:

[x*x if x % 2==0 else x * 3 for x in range(1,20)]

Thank you

It is customary to mark thread solved and you can also upvote (optionaly give reputation), if you like, good answers.

nice one.

list comprehension gives python the style and beauty with smooth power to do great tasks easy.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.