Join two arrays python

How do I concatenate two lists in Python?

This question’s answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.

listone = [1, 2, 3] listtwo = [4, 5, 6] 

Do you want to simply append, or do you want to merge the two lists in sorted order? What output do you expect for [1,3,6] and [2,4,5]? Can we assume both sublists are already sorted (as in your example)?

. also what if the lists have duplicates e.g. [1,2,5] and [2,4,5,6] ? Do you want the duplicates included, excluded, or don’t-care?

I made a youtube tutorial on 6 ways to concatenate lists if anyone finds it useful youtube.com/watch?v=O5kJ1v9XrDw

31 Answers 31

Use the + operator to combine the lists:

listone = [1, 2, 3] listtwo = [4, 5, 6] joinedlist = listone + listtwo 

@Daniel it will create a new list with a shallow copy of the items in the first list, followed by a shallow copy of the items in the second list. Use copy.deepcopy to get deep copies of lists.

@br1ckb0t will that change what listone is pointing at? So: list3 = listone listone+=listtwo Is list3 changed as well?

@Pygmalion That is not Python3 specific, but specific to how NumPy arrays handle operators. See the answer by J.F. Sebastian in the answer by Robert Rossney for concatenating NumPy arrays.

Читайте также:  Abstract modifier in java

Python >= 3.5 alternative: [*l1, *l2]

Another alternative has been introduced via the acceptance of PEP 448 which deserves mentioning.

The PEP, titled Additional Unpacking Generalizations, generally reduced some syntactic restrictions when using the starred * expression in Python; with it, joining two lists (applies to any iterable) can now also be done with:

>>> l1 = [1, 2, 3] >>> l2 = [4, 5, 6] >>> joined_list = [*l1, *l2] # unpack both iterables in a list literal >>> print(joined_list) [1, 2, 3, 4, 5, 6] 

This functionality was defined for Python 3.5, but it hasn’t been backported to previous versions in the 3.x family. In unsupported versions a SyntaxError is going to be raised.

As with the other approaches, this too creates as shallow copy of the elements in the corresponding lists.

The upside to this approach is that you really don’t need lists in order to perform it; anything that is iterable will do. As stated in the PEP:

This is also useful as a more readable way of summing iterables into a list, such as my_list + list(my_tuple) + list(my_range) which is now equivalent to just [*my_list, *my_tuple, *my_range] .

So while addition with + would raise a TypeError due to type mismatch:

l = [1, 2, 3] r = range(4, 7) res = l + r 

because it will first unpack the contents of the iterables and then simply create a list from the contents.

Источник

6 Ways to Concatenate Lists in Python

6 Ways to Concatenate Lists in Python

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

  • concatenation (+) operator
  • Naive Method
  • List Comprehension
  • extend() method
  • ‘*’ operator
  • itertools.chain() method

1. Concatenation operator (+) for List Concatenation

The ‘+’ operator can be used to concatenate two lists. It appends one list at the end of the other list and results in a new list as output.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = list1 + list2 print ("Concatenated list:\n" + str(res)) 
Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

2. Naive Method for List Concatenation

In the Naive method, a for loop is used to traverse the second list. After this, the elements from the second list get appended to the first list. The first list results out to be the concatenation of the first and the second list.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] print("List1 before Concatenation:\n" + str(list1)) for x in list2 : list1.append(x) print ("Concatenated list i.e. list1 after concatenation:\n" + str(list1)) 
List1 before Concatenation: [10, 11, 12, 13, 14] Concatenated list i.e. list1 after concatenation: [10, 11, 12, 13, 14, 20, 30, 42] 

3. List Comprehension to concatenate lists

Python List Comprehension is an alternative method to concatenate two lists in Python. List Comprehension is basically the process of building/generating a list of elements based on an existing list.

It uses for loop to process and traverses the list in an element-wise fashion. The below inline for-loop is equivalent to a nested for loop.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = [j for i in [list1, list2] for j in i] print ("Concatenated list:\n"+ str(res)) 
Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

4.Python extend() method for List Concatenation

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.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] print("list1 before concatenation:\n" + str(list1)) list1.extend(list2) print ("Concatenated list i.e ,ist1 after concatenation:\n"+ str(list1)) 

All the elements of the list2 get appended to list1 and thus the list1 gets updated and results as output.

list1 before concatenation: [10, 11, 12, 13, 14] Concatenated list i.e ,ist1 after concatenation: [10, 11, 12, 13, 14, 20, 30, 42] 

5. Python ‘*’ operator for List Concatenation

Python’s ‘*’ operator can be used to easily concatenate two lists in Python.

The ‘*’ operator in Python basically unpacks the collection of items at the index arguments.

For example: Consider a list my_list = [1, 2, 3, 4].

The statement *my_list would replace the list with its elements at the index positions. Thus, it unpacks the items of the lists.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = [*list1, *list2] print ("Concatenated list:\n " + str(res)) 

In the above snippet of code, the statement res = [*list1, *list2] replaces the list1 and list2 with the items in the given order i.e. elements of list1 after elements of list2. This performs concatenation and results in the below output.

Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

6. Python itertools.chain() method to concatenate lists

Python itertools modules’ itertools.chain() function can also be used to concatenate lists in Python.

The itertools.chain() function accepts different iterables such as lists, string, tuples, etc as parameters and gives a sequence of them as output.

It results out to be a linear sequence. The data type of the elements doesn’t affect the functioning of the chain() method.

For example: The statement itertools.chain([1, 2], [‘John’, ‘Bunny’]) would produce the following output: 1 2 John Bunny

import itertools list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = list(itertools.chain(list1, list2)) print ("Concatenated list:\n " + str(res)) 
Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

Conclusion

Thus, in this article, we have understood and implemented different ways of Concatenating lists in Python.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью