Python Group elements at same indices in a multi-list


In this tutorial, we are going to write a program that combines elements of the same indices different lists into a single list. And there is one constraint here. All the lists must be of the same length. Let's see an example to understand it more clearly.

Input

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

Output

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

We can solve it in different ways. Let's see how to solve with normal loops.

  • Initialize the list with lists.
  • Initialize an empty list.
  • Initialize a variable index to 0.
  • Iterate over the sub list length times
    • Append an empty list to the previous list
    • Iterate lists length times.
      • Append the **lists[current_index][index]** to the **result[index]
  • Print the result.

Example

 Live Demo

# initializing the list
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# empty list
result = []
# variable to 0
index = 0
# iterating over the sub_list length (3) times
for i in range(len(lists[0])):
   # appending an empty sub_list
   result.append([])
   # iterating lists length (3) times
   for j in range(len(lists)):
      # adding the element to the result
      result[index].append(lists[j][index])
# moving to the next index
index += 1
# printing the result
print(result)

Output

If you run the above code, then you will get the following result.

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

We can solve it using the zip function without any effort. The zip function gives you all the index elements in a tuple as we want. Let's see the code.

Example

 Live Demo

# initializing the list
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# using the zip and printing it
print(list(zip(*lists)))

Output

If you run the above code, then you will get the following result.

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

We can convert the tuples into the list by iterating through the lists. It can be done differently.will use another function called map to convert all tuples into lists. It's one line code.

Example

 Live Demo

# initializing the list
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# using the zip and printing it
print(list(map(list, zip(*lists))))

Output

If you run the above code, then you will get the following result.

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

We have used map to iterate through the list and convert each tuple into the list. You can do same with loops. Try it.

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

Updated on: 06-Jul-2020

511 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements