Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the concatenation of two lists in Python without modifying either one? [duplicate]

In Python, the only way I can find to concatenate two lists is list.extend, which modifies the first list. Is there any concatenation function that returns its result without modifying its arguments?

like image 932
Ryan C. Thompson Avatar asked Dec 03 '10 09:12

Ryan C. Thompson


People also ask

How do you concatenate two lists without duplicates in Python?

Python merges two lists without duplicates could be accomplished by using a set. And use the + operator to merge it.

How do I combine two lists without duplicates?

You can also merge lists without duplicates in Google Sheets. Select and right-click a second range that will be merged (e.g., C2:C6) and click Copy (or use the keyboard shortcut CTRL + C).

Can we concatenate 2 lists in Python?

Python's extend() method can be used to concatenate two lists in Python. The extend() function does iterate over the passed parameter and adds the item to the list thus, extending the list in a linear fashion. All the elements of the list2 get appended to list1 and thus the list1 gets updated and results as output.


2 Answers

Yes: list1 + list2. This gives a new list that is the concatenation of list1 and list2.

like image 119
NPE Avatar answered Sep 20 '22 09:09

NPE


The simplest method is just to use the + operator, which returns the concatenation of the lists:

concat = first_list + second_list

One disadvantage of this method is that twice the memory is now being used . For very large lists, depending on how you're going to use it once it's created, itertools.chain might be your best bet:

>>> import itertools >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = itertools.chain(a, b) 

This creates a generator for the items in the combined list, which has the advantage that no new list needs to be created, but you can still use c as though it were the concatenation of the two lists:

>>> for i in c: ...     print i 1 2 3 4 5 6 

If your lists are large and efficiency is a concern then this and other methods from the itertools module are very handy to know.

Note that this example uses up the items in c, so you'd need to reinitialise it before you can reuse it. Of course you can just use list(c) to create the full list, but that will create a new list in memory.

like image 43
Scott Griffiths Avatar answered Sep 23 '22 09:09

Scott Griffiths