Gabriel Gomide
Gabriel Gomide

Reputation: 11

Join list of lists and strings into a list

I'm having an issue to join lists.

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

I need this:

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

Upvotes: 0

Views: 45

Answers (1)

eumiro
eumiro

Reputation: 212875

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)

Upvotes: 0

Related Questions