Search code examples
pythonpython-3.xlistfor-looplist-comprehension

if else in list comprehension with for loop


I've written my own simple solution for flatten list:

lists = [0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120]]
new = []
for item in lists:
    if str(item).isdigit() != True:
        for v in item:
            new.append(v)
    else:
        new.append(item)
print(new)

But I want to add an else/elif to the following code to make code shorter:

new = [v for item in lists if str(item).isdigit() != True for v in item]

I don't know how to rather getting syntax errors.


Solution

  • First some notes for your original code:

    1. Instead of

      if str(item).isdigit() != True:
      

      use more Pythonic

      if not str(item).isdigit():
      
    2. Instead of the same, speculative way to reach your goal, use more clear

      if type(item) is not list:
      

    Now, about else in list comprehension. It may be only in the first part of it, syntax of list comprehension don't allow it after the for clause (in if filtering expressions).

    So you need to change the iterable in the second for of your list comprehension to always be an iterable, i.e. for example for item

    • [20, 30] it is OK (because it is an iterable)
    • 10 it is not OK (because it is not an iterable) - so let's put bracket around it - [10]

    So we will switch between item and [item] depending of type(item):

     item     if type(item) is list     else     [item]
    

    (It is a conditional expression, not a list comprehension, so else is OK here.)

    So the full solution may be

    new = [v for item in lists 
             for v in (item if type(item) is list else [item])]