0

I'm having an issue to join lists.

list = ['a','b',['c','d'],['e']]

I need this:

list = ['a','b','c','d','e']
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • This is a different question than https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists – eumiro Apr 26 '20 at 13:27
  • Dupe: [https://stackoverflow.com/questions/17864466/flatten-a-list-of-strings-and-lists-of-strings-and-lists-in-python](https://stackoverflow.com/questions/17864466/flatten-a-list-of-strings-and-lists-of-strings-and-lists-in-python) – Patrick Artner Apr 26 '20 at 13:32

1 Answers1

1

Don't use the list as a variable name (it would even break my code example):

import itertools as it
items = ['a','b',['c','d'],['e']]

# in a single line:

flat = list(it.chain.from_iterable([item if isinstance(item, list) else [item] for item in items])) 

# or in several lines:
flat = []
for item in items:
    if isinstance(item, list):
        flat.extend(item)
    else:
        flat.append(item)
eumiro
  • 207,213
  • 34
  • 299
  • 261