This question already has answers here: Closed 9 years ago. The community reviewed whether to reopen this question 11 months ago and left it closed: Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
Possible Duplicate: Making a flat list out of list of lists in Python Join a list of lists together into one list in Python
I have many lists which looks like
['it']
['was']
['annoying']
I want the above to look like
['it', 'was', 'annoying']
How do I achieve that?
import itertools
ab = itertools.chain(['it'], ['was'], ['annoying'])
list(ab)
Just another method....
Just add them:
['it'] + ['was'] + ['annoying']
You should read the Python tutorial to learn basic info like this.
mylist = list(set(mylist))
after merging lists to get rid of the duplicates.
sum(mylist, [])
but it is not very optimize.
reduce(lambda l1, l2: l1+l2, lists)
where lists
is a list or a tuple of the lists.
a = ['it']
b = ['was']
c = ['annoying']
a.extend(b)
a.extend(c)
# a now equals ['it', 'was', 'annoying']
Success story sharing
list(itertools.chain(['it'], ['was'], ['annoying']))
gives['it', 'was', 'annnoying']
. Is that different from what you want?from_iterable
function such asab = list(itertools.chain.from_iterable([['it'], ['was'], ['annoying']]))
would be give the answer the OP expects*args
by saying:itertools.chain(*my_list_of_lists)
.from_iterable
it accepts any iterable, which can be e.g. generator returning subsequent lists.