1

I am trying to combine n number of arrays like this in python 3:

Example input:

l1 =["a", "b", "c"]
l2 = [1, 2, 3]
l3 = ["!", "@", "#"]

Example output:

[['a', 1, '!'], ['b', 2, '@'], ['c', 3, '#']]

Heres what I have written that works for three given inputs, however I need this to work for n number of lists:

def assemble_three_lists(list1, list2, list3):
combined_list = []
list1_length = len(list1)
list2_length = len(list2)
list3_length = len(list3)

if list1_length != list2_length and list1_length != list3_length:
    raise Exception("Some elements have been lost, critical error.")
else:
    i = 0
    while i < list1_length:
        combined_list.insert(i, [list1[i], list2[i], list3[i]])
        i += 1
return combined_list

I have tried writing it like this:

def assemble_lists(list_of_lists):
return [list[::] for list in list_of_lists]

But my output was:

[['a', 'b', 'c']], [[1, 2, 3]], [['!', '@', '#']]
martineau
  • 119,623
  • 25
  • 170
  • 301
Ryan Bircham
  • 67
  • 1
  • 6

1 Answers1

2

You can use zip() for that:

l1 =["a", "b", "c"]
l2 = [1, 2, 3]
l3 = ["!", "@", "#"]

print(*zip(l1,l2,l3))
# ('a', 1, '!') ('b', 2, '@') ('c', 3, '#')

If you really need a list of lists:

print([list(i) for i in zip(l1,l2,l3)])
# [['a', 1, '!'], ['b', 2, '@'], ['c', 3, '#']]
Andreas
  • 8,694
  • 3
  • 14
  • 38