Reputation: 29
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?
Upvotes: 2
Views: 67
Reputation: 1852
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)]
Upvotes: 2
Reputation: 289
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']]
Upvotes: 1
Reputation: 914
All your lists list_1
,list_2
and list_3
are of equal length
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)
Upvotes: 0