0

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?

3
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by richieking
1

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)]
0

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

0

nice one.

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.