How can I get the concatenation of two lists in Python without modifying either one?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Meditation
--
Chapters
00:00 How Can I Get The Concatenation Of Two Lists In Python Without Modifying Either One?
00:23 Accepted Answer Score 1151
00:40 Answer 2 Score 174
01:52 Answer 3 Score 117
02:06 Answer 4 Score 102
02:41 Answer 5 Score 45
03:01 Thank you
--
Full question
https://stackoverflow.com/questions/4344...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #concatenation #sequence #listmanipulation
#avk47
ACCEPTED ANSWER
Score 1151
Yes: list1 + list2. This gives a new list that is the concatenation of list1 and list2.
ANSWER 2
Score 174
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.
ANSWER 3
Score 117
concatenated_list = list_1 + list_2
ANSWER 4
Score 45
you could always create a new list which is a result of adding two lists.
>>> k = [1,2,3] + [4,7,9]
>>> k
[1, 2, 3, 4, 7, 9]
Lists are mutable sequences so I guess it makes sense to modify the original lists by extend or append.