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?
Python merges two lists without duplicates could be accomplished by using a set. And use the + operator to merge it.
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).
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.
Yes: list1 + list2
. This gives a new list that is the concatenation of list1
and list2
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With