Python Group elements at same indices in a multi-list

In this tutorial, we will write a program that groups elements at the same indices from multiple lists into a single list. This operation is also known as transposing a matrix. All input lists must have the same length.

Example Input and Output

Let's see what we want to achieve ?

# Input
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Output  
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Elements at index 0 from all lists: [1, 4, 7], elements at index 1: [2, 5, 8], and so on.

Method 1: Using Nested Loops

We can solve this step by step using nested loops ?

# initializing the list
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# empty result list
result = []

# iterating over the sub_list length (3) times
for i in range(len(lists[0])):
    # appending an empty sub_list for current index
    result.append([])
    
    # iterating through each list
    for j in range(len(lists)):
        # adding the element at index i from list j
        result[i].append(lists[j][i])

# printing the result
print(result)
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Method 2: Using zip() Function

Python's zip() function provides an elegant solution. The * operator unpacks the lists ?

# initializing the list
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# using zip with unpacking
result = list(zip(*lists))
print(result)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

Method 3: Converting Tuples to Lists

If you need lists instead of tuples, use map() to convert each tuple ?

# initializing the list
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# using zip and map to get lists
result = list(map(list, zip(*lists)))
print(result)
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Comparison

Method Readability Performance Output Type
Nested Loops Verbose Slower Lists
zip(*lists) Concise Faster Tuples
map(list, zip(*lists)) Concise Fast Lists

Conclusion

Use zip(*lists) for the most Pythonic solution. Use map(list, zip(*lists)) when you specifically need lists instead of tuples.

Updated on: 2026-03-25T08:59:14+05:30

742 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements