-1

I currently have a list like this:

[3, 4, ['x', 'y', 'z'], 5]

and want to make it to

[3, 4, 'x', 'y', 'z', 5]

New beginner at this, and tried searching around, but couldn't find anything I could understand.

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225

1 Answers1

0
l=[3, 4, ['x', 'y', 'z'], 5]
nl=[]
for x in l:
    if not isinstance(x,int):
        for y in x:
            nl.append(y)
    else:
        nl.append(x)

print(nl)

One liner

l=[3, 4, ['x', 'y', 'z'], 5]
nl=[];[nl.extend([x] if isinstance(x,int) else x) for x in l]

It is not flatening list of list because the given one is combination of list and int

Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
  • [isinstance](https://docs.python.org/3/library/functions.html#isinstance) "...is recommended for testing the type of an object..." – wwii Oct 16 '16 at 04:50
  • Your "one-liner" is an example of when NOT to use list comprehensions. Do not mix imperative techniques (mutating a data structure: i.e. `list.exend`) with functional constructs, i.e. list comprehensions. Also, it is generally considered unpythonic to use multiple statements per line, seperated by a semicolon, like that. Readability counts. – juanpa.arrivillaga Oct 16 '16 at 07:34