2

Say I have the following lists:

list_1 = [1, 2, 3]
list_2 = ['a', 'b', 'c']
list_3 = ['red', 'yellow', 'blue']

And I want to create one list of lists, as follows:

combined_list = [[1, 'a', 'red'],
                 [2, 'b', 'yellow'],
                 [3, 'c', 'blue']]

What is the best way of going about this?

Umar Hussain
  • 3,461
  • 1
  • 16
  • 38
Lola Tesla
  • 29
  • 4
  • Does this answer your question? [Matrix Transpose in Python](https://stackoverflow.com/questions/4937491/matrix-transpose-in-python) – AMC Feb 27 '20 at 02:11
  • It's not an **exact** duplicate but it's incredibly close, and the core of the solution (`zip()`) is what matters. – AMC Feb 27 '20 at 02:12

3 Answers3

2

Just use zip. You will need to cast each produced tuple into a list and use a list comprehension as the following example:

combined_list = [list(tuple) for tuple in zip(list_1, list_2, list_3)]
kebab-case
  • 1,732
  • 1
  • 13
  • 24
1
list_1 = [1, 2, 3] 
list_2 = ['a', 'b', 'c'] 
list_3 = ['red', 'yellow', 'blue']

combined_list = []
combined_list+=map(list, zip(list_1, list_2, list_3))
print(combined_list)

Result:

[[1, 'a', 'red'], [2, 'b', 'yellow'], [3, 'c', 'blue']]
0

ASSUMPTIONS:

All your lists list_1,list_2 and list_3 are of equal length

Solution

You simply iterate through the list and append the combined list for each index to an an empty list

def combine(l1,l2,l3):
    res = []
    for i in range(len(l1)):
        res.append([l1[i],l2[i],l3[i]])
    return res

Now you can simply call this function with your lists list_1, list_2 and list_3 like this

combined = combine(list_1,list_2,list_3)
sudo97
  • 904
  • 2
  • 11
  • 22