'How to generate a list comprehension with a conditional where the conditional is a NameError

Suppose the following list:

l = ['1','2','M']

How can I transform l to l_1 via a list comprehension?

l_1 = [1, 2, 'M']

I attempted the below without success.

[eval(c) if eval(c) not NameError else c for c in l]

  File "<ipython-input-241-7c3f63ffe51b>", line 1
    [eval(c) if c not NameError else c for c in list(a)]
                      ^
SyntaxError: invalid syntax


Solution 1:[1]

Hi,

You could validate each element of the list l as strings, even if you already have some digits on it such as l = ['1','2','M',3,'p'], that way you have that validation there by passing them all to string and then verifying if the element is digit, and if so, you pass it to int, of float, or number to the new l_1 and if it is not, you simply pass it as string. In this case I will convert each numeric element to int, but you could choose to pass it to number in any other type such as float, for example, if the list contains floating elements.

l = ['1','2','M',3,'p']
l_1 = [int(el) if str(el).isdigit() else el for el in l]
print(l_1)

I certainly hope this helps, good luck and keep coding, it's always fun!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alvison Hunter