Add two lists 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.

Читайте также:  Variable in css selector

@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.

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.

Источник

Python Add Lists

This tutorial covers the following topic – Python Add lists. It describes various ways to join/concatenate/add lists in Python. For example – simply appending elements of one list to the tail of the other in a for loop, or using +/* operators, list comprehension, extend(), and itertools.chain() methods.

Most of these techniques use built-in constructs in Python. However, the one, itertools.chain() is a method defined in the itertools module. You must also see which of these ways is more suitable for your scenario. After going through this post, you can evaluate their performance in the case of large lists.

By the way, it will be useful if you have some elementary knowledge about the Python list. If not, please go through the linked tutorial.

Python Add Lists – 6 Ways to Join/Concatenate Lists

For loop to add two lists

It is the most straightforward programming technique for adding two lists.

  • Traverse the second list using a for loop
  • Keep appending elements in the first list
  • The first list would expand dynamically

Finally, you’ll have a single list having all the items from other lists.

# Python Add lists example # Sample code to add two lists using for loop # Test input lists in_list1 = [21, 14, 35, 16, 55] in_list2 = [32, 25, 71, 24, 56] # Using for loop to add lists for i in in_list2 : in_list1.append(i) # Displaying final list print («\nResult: **********\nConcatenated list using for loop: » + str(in_list1))

python add lists using for loop

Plus (+) operator to merge two lists

Many languages use the + operator for appending/merging strings. Python supports it also, and even for lists.

It is a straightforward merge operation using the “+” operator. And you can easily merge lists by adding one to the back of the other.

# Python merge lists # Sample code to merge two lists using + operator # Test input lists in_list1 = [21, 14, 35, 16, 55] in_list2 = [32, 25, 71, 24, 56] # Apply + operator to merge lists in_list3 = in_list1 + in_list2 # Displaying final list print ("\nResult: **********\nPython merge list using + operator: " + str(in_list3))

python merge lists using plus operator

Mul (*) operator to join lists

It’s entirely a new method to join two or more lists and is available from Python 3.6. You can apply it to concatenate multiple lists and deliver one unified list.

# Python join two lists # Sample code to join lists using * operator # Test input lists in_list1 = [21, 14, 35, 16, 55] in_list2 = [32, 25, 71, 24, 56] # Apply * operator to join lists in_list3 = [*in_list1, *in_list2] # Displaying final list print («\nResult: **********\nPython join list using * operator: » + str(in_list3))

python join lists using star operator

List comprehension to concatenate lists

List comprehension allows any operation (concatenation) on the input lists and can produce a new one without much effort. This method processes the list like in a “for” loop, i.e., element by element.

# Python concatenate two lists # Sample code to concatenate lists using list comprehension # Test input lists in_list1 = [21, 14, 35, 16, 55] in_list2 = [32, 25, 71, 24, 56] # Apply list comprehension to concatenate lists in_list3 = [n for m in [in_list1, in_list2] for n in m] # Displaying final list print ("\nResult: **********\nPython concatenate list using list comprehension: " + str(in_list3))

python concatenate list using list comprehension

Built-in list extend() method

This function is a part of the Python list class and can also be used to add or merge two lists. It does an in-place expansion of the original list.

# Demonstrate Python Add lists # Sample code to add two lists using list.extend() # Test input lists in_list1 = [21, 14, 35, 16, 55] in_list2 = [32, 25, 71, 24, 56] # Using Python list.extend() method to add lists in_list1.extend(in_list2) # Displaying final list print ("\nResult: **********\nPython Add lists using list.extend(): " + str(in_list1))

python add lists using list extend method

itertools.chain() to combine lists

Python itertools chain() function takes multiple iterables and produces a single list. The output is the concatenation of all input lists into one. Let’s illustrate Python join lists with the help of a simple program.

# Sample code to join lists using itertools.chain() import itertools # Test input lists in_list1 = [21, 14, 35, 16, 55] in_list2 = [32, 25, 71, 24, 56] # Using itertools.chain() method to join lists in_list3 = list(itertools.chain(in_list1, in_list2)) # Displaying final list print («\nResult: **********\nPython join lists using itertools.chain(): » + str(in_list3))

python join lists using itertools chain method

You’ve seen various methods to add/join/merge/concatenate lists in Python. Now, you should evaluate which one fits the most in your scenario. Also, you can now evaluate them based on their speed in case of large data sets. By the way, to learn Python from scratch to depth, do read our step-by-step Python tutorial .

Источник

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.

Источник

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