89DEVs

Python: How to add two lists?

How to add two lists in Python?

To add two lists in Python several options are available. It is possible to add the same list or different lists. The lists can be combined to one list or the elements of the lists can be summed and the sums added to a new list.

add lists using + operator

To add lists in Python, use the + operator as shown below. # add lists using + operator myList = [1, 2, 3] print(myList + myList) The same list is added into one list, essentially doubling the elements in the list. [1, 2, 3, 1, 2, 3] The same result can be generated using the * operator as shown below. myList = [1, 2, 3] print(myList * 2) The list is multiplied and printed. [1, 2, 3, 1, 2, 3]

add lists using extend() method

To add lists in Python, use the list.extend() method as shown below. # add lists using the extend() method myList = [1, 2, 3] myList.extend(myList) print(myList) The same list is added, and the result is returned as a list. [1, 2, 3, 1, 2, 3]

add elements of lists

Above all elements of the lists have been added. To add the sum of the elements instead, use the zip() function as shown below. # add sum of elements to list list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [] for n1, n2 in zip(list1, list2): list3.append(n1 + n2) print(list3) Here, the elements of both lists are summed and then the sum is appended to the third list. [5, 7, 9] The same is possible with more than two lists. # add sum of elements of more than two lists list1 = [1, 2, 3] list2 = [2, 2, 2] list3 = [3, 3, 3] list4 = [] for n1, n2, n3 in zip(list1, list2, list3): list4.append(n1 + n2 + n3) print(list4) Now the elements of three lists are added and the sums are appended to a fourth list. [6, 7, 8]

add lists using list comprehension

The elements of lists can be added using list comprehension as shown below. List comprehensions are a concise way to execute the operation and are considered pythonic. # add lists using list comprehension list1 = [1, 2, 3] list2 = [6, 5, 4] list3 = [a + b for a, b in zip(list1, list2)] print(list3) In this example, list comprehension is used to sum the elements and store the results in list3. [7, 7, 7]

add lists using numpy arrays

Another way of adding two or more lists is by converting them into numpy.arrays and then adding them as shown below. # add lists using numpy arrays import numpy as np array1 = np.array([1, 2, 3]) array2 = np.array([6, 5, 4]) array3 = np.add(array1, array2) print(array3) The lists are converted into numpy arrays using the array() method of the numpy module. Then both arrays are added using the numpy.add() method. The results are saved to array3 and finally, array3 is printed. [7 7 7]

                
        

Summary


Click to jump to section