ChatGPT解决这个技术问题 Extra ChatGPT

How to merge multiple lists into one list in python? [duplicate]

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?

This isn't really a duplicate of that. That question is asking how to flatten a list of nested lists. This question is much more basic and is just asking how to concatenate individual lists.
@BrenBarn That is exactly what I'm asking.

R
Rakesh
import itertools
ab = itertools.chain(['it'], ['was'], ['annoying'])
list(ab)

Just another method....


Ok there is a file which has different words in 'em. I have done s = [word] to put each word of the file in list. But it creates separate lists (print s returns ['it]']['was']['annoying']) as I mentioned above. I want to merge all of them in one list.
@user1452759 list(itertools.chain(['it'], ['was'], ['annoying'])) gives ['it', 'was', 'annnoying']. Is that different from what you want?
If the input is a list of lists, using the from_iterable function such as ab = list(itertools.chain.from_iterable([['it'], ['was'], ['annoying']])) would be give the answer the OP expects
You could also pass it as an *args by saying: itertools.chain(*my_list_of_lists).
@BallpointBen No, because from_iterable it accepts any iterable, which can be e.g. generator returning subsequent lists.
B
BrenBarn

Just add them:

['it'] + ['was'] + ['annoying']

You should read the Python tutorial to learn basic info like this.


You solved the i=3 case, how about i=n?
@Full Decent, thanks for point this out, did not think about that i=n case. But I think if it is i=n case, can loop in the lists and concatenate them. For me, just need the most comma way to join 2 lists without duplication elements.
@zhihong Hey there, it's been well over a full year but you can use something like mylist = list(set(mylist)) after merging lists to get rid of the duplicates.
@WilliamEntriken , Technically you can use build in sum for example sum(mylist, []) but it is not very optimize.
For i=n case, you can also use reduce(lambda l1, l2: l1+l2, lists) where lists is a list or a tuple of the lists.
S
Scotty
a = ['it']
b = ['was']
c = ['annoying']

a.extend(b)
a.extend(c)

# a now equals ['it', 'was', 'annoying']

Yes, But if you are not sure about the length of the list (which is to be used to extend the main list) then how am I going to extend ? Is it anyway possible to use slicing method to deal with variable length lists ?