Python Concatenate two lists elementwise (original) (raw)

Python – Concatenate two lists element-wise

Last Updated : 17 Dec, 2024

In Python, concatenating two lists element-wise means merging their elements in pairs. This is useful when we need to combine data from two lists into one just like joining first names and last names to create full names. zip() function is one of the most efficient ways to combine two lists element-wise. It pairs up elements from two lists and allows us to perform operations on these pairs.

Python `

a = [1, 2, 3] b = ['a', 'b', 'c']

Use zip() to pair the elements

result = [str(x) + str(y) for x, y in zip(a, b)]

print(result)

`

Other methods that we can use to concatenate two lists element-wise in Python are:

Table of Content

Using List Comprehension

List comprehension is another efficient and compact way to concatenate two lists element-wise. It is concise and easy to understand.

Python `

a = [1, 2, 3] b = ['a', 'b', 'c']

Use list comprehension to concatenate element-wise

result = [str(a[i]) + str(b[i]) for i in range(len(a))]

print(result)

`

Using the map() Function

map() is another functional approach where we apply a function to each element of two lists. It can be a bit more advanced but works well in more complex scenarios.

Python `

a = [1, 2, 3] b = ['a', 'b', 'c']

Use map() to concatenate elements

result = list(map(lambda x, y: str(x) + str(y), a, b))

print(result)

`

Using a Loop

The loop is the most basic way to concatenate two lists element-wise. It is less efficient for larger lists compared to the previous methods.

Python `

a = [1, 2, 3] b = ['a', 'b', 'c']

Create an empty list to store the result

result = []

Loop through the lists and concatenate element-wise

for i in range(len(a)): result.append(str(a[i]) + str(b[i]))

print(result)

`

Using numpy Arrays

If you’re working with numerical data and need high performance, numpy arrays provide an efficient way to concatenate two lists element-wise. This method is particularly fast for large lists of numbers.

Python `

import numpy as np

a = [1, 2, 3] b = ['a', 'b', 'c']

Convert the lists to numpy arrays

a = np.array(a, dtype=str) b = np.array(b, dtype=str)

Use numpy's vectorized operation to concatenate

result = np.core.defchararray.add(a, b)

print(result)

`

Similar Reads

Python List Access





List Iteration Operations





Python List Search Operations






Python List Remove Operations






Python List Concatenation Operations