Search code examples
python-3.xlist-comprehension

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

  • Assuming your general case looks like this, you could use isdigit to only convert numbers.

    l=['1','2','M']
    l1=[int(c) if c.isdigit() else c for c in l]