+ 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
+ 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
+ 3
Gordon I'm sure đâșïž
7th Jan 2019, 11:54 AM
Anna
+ 1