
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Concatenate Two Lists Element-wise in Python
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
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
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']
Advertisements