Search code snippets, questions, articles...

Add two list items with their respective index in python

Python lists are one of the most important data structures in Python. They are one of the main ways to represent sequences of values. In this tutorial, we will be looking at how to add two list items to each other.
list1 = [5, 4, 6, 8]
list2 = [10, 5, 12, 3]

result = list(map(lambda a, b: a + b, list1, list2))

# -> [15, 9, 18, 11]
[15, 9, 18, 11]

We are using lambda and map functions of python to generate the new list that contains the sum of two lists. Read more about map and lambda functions from the below links.

What is the map() function in python

Lambda Functions in python

We have two lists here list1 and list2. Both of the lists contain integer type values and the syntax that is used to add the list is

list(map(lambda a, b: a + b, list1, list2))

This can also be done without using the lambda function. We will use the python function for that as the below example.

list1 = [7, 9, 8, 13]
list2 = [13, 15, 12, 13]

def add(x, y):
  return x + y

result = list(map(add, list1, list2))

# -> [20, 24, 20, 26]

In the above code, we are using the function named as add in place of a lambda function.

Search Index Data (The code snippet can also be found with below search text)

add two list items in python
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
list3 = [9, 10, 11, 12]

result = list(map(lambda a, b, c: a + b + c, list1, list2, list3))

# -> [15, 18, 21, 24]
We can add more than two list using lambda and map function with single line of code as shown in the above code example.
Was this helpful?
Programming Feeds
Learn something new everyday on Devsheet