Search code examples
pythonlistpython-3.xfor-comprehension

How to convert to Python list comprehension


ls = ['abc', 56, 49, 63, 66, 80]
for i in ls:
    if(isinstance(i, int) or isinstance(i, float)):
        for i in range(len(ls)):
            ls[i] = str(ls[i])

May I know how to create the list comprehension of above code?

I am trying the following but not working

if (s for s in ls isinstance(s, int) or isinstance(s, float)):
    for i in range(len(ls)):
        ls[i] = str(ls[i])

Solution

  • For your example where you have either strings or integers or floats, you can use a simple list comprehension:

    ls = ['abc', 56, 49, 63, 66, 80]
    print([str(l) for l in ls])
    

    Or alternatively, you can use map:

    print(list(map(str, ls)))
    

    If you only want to convert floats and integers to strings (and ignore anything else like booleans, decimal objects, etc.):

    print([str(l) if isinstance(l, int) or isinstance(l, float) else l for l in ls])