Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Concatenate two lists element-wise in Python
Python 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.
Using zip() with List Comprehension
The zip() function pairs elements from two lists, allowing us to concatenate them element-wise. We can use list comprehension to create a new list with concatenated elements ?
list_a = ["Outer-", "Frost-", "Sun-"]
list_b = ['Space', 'bite', 'rise']
# Given lists
print("Given list A:", list_a)
print("Given list B:", list_b)
# Use zip with list comprehension
result = [i + j for i, j in zip(list_a, list_b)]
# Result
print("The concatenated lists:", result)
Given list A: ['Outer-', 'Frost-', 'Sun-'] Given list B: ['Space', 'bite', 'rise'] The concatenated lists: ['Outer-Space', 'Frost-bite', 'Sun-rise']
Using map() with Lambda Function
The map() function applies a lambda function to each pair of elements from both lists. This approach uses functional programming to achieve the same result ?
list_a = ["Outer-", "Frost-", "Sun-"]
list_b = ['Space', 'bite', 'rise']
# Given lists
print("Given list A:", list_a)
print("Given list B:", list_b)
# Use map with lambda
result = list(map(lambda x: x[0] + x[1], zip(list_a, list_b)))
# Result
print("The concatenated lists:", result)
Given list A: ['Outer-', 'Frost-', 'Sun-'] Given list B: ['Space', 'bite', 'rise'] The concatenated lists: ['Outer-Space', 'Frost-bite', 'Sun-rise']
Using operator.add with map()
For string concatenation, we can use the operator.add function with map() for a more readable approach ?
import operator
list_a = ["Outer-", "Frost-", "Sun-"]
list_b = ['Space', 'bite', 'rise']
# Given lists
print("Given list A:", list_a)
print("Given list B:", list_b)
# Use operator.add with map
result = list(map(operator.add, list_a, list_b))
# Result
print("The concatenated lists:", result)
Given list A: ['Outer-', 'Frost-', 'Sun-'] Given list B: ['Space', 'bite', 'rise'] The concatenated lists: ['Outer-Space', 'Frost-bite', 'Sun-rise']
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fast | Simple concatenation |
| map() + lambda | Medium | Good | Functional programming |
| map() + operator.add | High | Fast | Clean, readable code |
Conclusion
List comprehension with zip() is the most Pythonic and readable approach for element-wise concatenation. Use map() with operator.add for functional programming style or when working with large datasets.
