Concatenate two lists element-wise in Python

PythonServer Side ProgrammingProgramming

Pyhton has great data manipulation features. In this article we will see how to combine the elements from two lists in the same order as they are present in the lists.

With zip

The zip function can take in the two lists as parameters and concatenate them. We design a for loop to capture these combinations and put them into a new list.

Example

 Live Demo

listA = ["Outer-", "Frost-", "Sun-"]
listB = ['Space', 'bite', 'rise']
# Given lists
print("Given list A: ", listA)
print("Given list B: ",listB)
# Use zip
res = [i + j for i, j in zip(listA, listB)]
# Result
print("The concatenated lists: ",res)

Output

Running the above code gives us the following result −

Given list A: ['Outer-', 'Frost-', 'Sun-']
Given list B: ['Space', 'bite', 'rise']
The concatenated lists: ['Outer-Space', 'Frost-bite', 'Sun-rise']

With lambda and map

The map function will apply the same function again and again to the parameters passed onto it. We will also use a lambda function to combine the individual elements one by one from the two lists through zip.

Example

 Live Demo

listA = ["Outer-", "Frost-", "Sun-"]
listB = ['Space', 'bite', 'rise']
# Given lists
print("Given list A: ", listA)
print("Given list B: ",listB)
# Use map
res = list(map(lambda(i, j): i + j, zip(listA, listB)))
# Result
print("The concatenated lists: ",res)

Output

Running the above code gives us the following result −

Given list A: ['Outer-', 'Frost-', 'Sun-']
Given list B: ['Space', 'bite', 'rise']
The concatenated lists: ['Outer-Space', 'Frost-bite', 'Sun-rise']
raja
Published on 20-May-2020 13:57:39
Advertisements