List comprehension | Sololearn: Learn to code for FREE!


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]

1/7/2019 7:40:16 AM

Bishu Giri

5 Answers

New Answer


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


Gordon I'm sure πŸ‘Œβ˜ΊοΈ


Wow, but can he understand your answer? πŸ˜…


Thanks Anna was helpful:)


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]