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
Selected Reading
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.
Advertisements
