List comprehension | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

List comprehension

Is it possible to do try and except using list comprehension in python? For example : I have list [1,2,3,'h',4], I would like to calculate square of all integers and keep 'h' as it is. [1, 4, 9,'h', 16]

7th Jan 2019, 7:40 AM
Bishu Giri
Bishu Giri - avatar
5 Answers
+ 8
I don't think you can use try/except in a list comprehension, but you don't need to because you can get the desired result with if/else: lst = [1, 2, 3, 'h', 4] squares = [n**2 if isinstance(n, int) or isinstance(n, float) else n for n in lst] print(squares) # [1, 4, 9, 'h', 16] /Edit: This one makes it easier to add more numeric data types: squares2 = [n**2 if any(isinstance(n, t) for t in (int, float)) else n for n in lst] print(squares2) /Edit²: using numbers.Number will detect most numerical types: from numbers import Number lst = [1, 2, 3, 4.5, 'h', 6, 7j] squares3 = [n**2 if isinstance(n, Number) else n for n in lst] print(squares3) # [1, 4, 9, 20.25, 'h', 36, (-49+0j)]
7th Jan 2019, 8:14 AM
Anna
Anna - avatar
+ 3
Gordon I'm sure 👌☺️
7th Jan 2019, 11:54 AM
Anna
Anna - avatar
+ 1
Wow, but can he understand your answer? 😅
7th Jan 2019, 11:42 AM
Gordon
Gordon - avatar
+ 1
Thanks Anna ..it was helpful:)
7th Jan 2019, 12:40 PM
Bishu Giri
Bishu Giri - avatar
0
If it's only about int or not int, I would use this pattern: [i**2 if type(i)==int else i for i in l]
7th Jan 2019, 1:30 PM
HonFu
HonFu - avatar