What are the differences between zip creating a list of lists or tuples?

Hi,

I haven’t posted in the forum before so I’m not sure if I’m posting the correct thread (also sorry for necroing). In regards to the zip() function. It is stated that it merges multiple lists into a list of lists, except that [(a,b),(a,b)] is a list of tuples. Is there a way to actually create a list of lists [[a,b],[a,b],[a,b]]?

names = ['Jenny', 'Alexus', 'Sam', 'Grace']
dogs_names = ['Elphonse', 'Dr. Doggy DDS', 'Carter', 'Ralph']

names_and_dogs_names = zip(names, dogs_names)

list_of_names_and_dogs_names = list(names_and_dogs_names)

print(type(list_of_names_and_dogs_names[0]))

Output would be: <class ‘tuple’>

Thanks!

Both sequences are essentially the same, save for not being able to mutate a tuple. They are both ordered and both can be iterated with the same methods.

list_of_lists = [[a, b] for (a, b) in zip(names, dogs_names)]

Eg.

>>> names = ['Jenny', 'Alexus', 'Sam', 'Grace']
>>> dogs_names = ['Elphonse', 'Dr. Doggy DDS', 'Carter', 'Ralph']
>>> [[a, b] for (a, b) in zip(names, dogs_names)]
[['Jenny', 'Elphonse'], ['Alexus', 'Dr. Doggy DDS'], ['Sam', 'Carter'], ['Grace', 'Ralph']]
>>> 

Correction

Tuples cannot be zipped, likely owing to immutability, perhaps?


They can both be unpacked

>>> p = (1,2,3)
>>> q,r,s = p
>>> q
1
>>> r
2
>>> s
3
>>> p = [4,5,6]
>>> q,r,s = p
>>> q
4
>>> r
5
>>> s
6
>>> 
7 Likes

As I’ve tried one can zip both lists and tuples or mix them in one zip

In [4]: myList = ['a', 'b', 'c']                                                                                      

In [5]: myTuple = ('d', 'e', 'f')                                                                                     

In [6]: print(list(zip(myList, myTuple)))                                                                             
[('a', 'd'), ('b', 'e'), ('c', 'f')]

In [7]: tuple1 = (1, 2, 3) 
In [8]: tuple2 = (4, 5, 6)                                                                                            

In [9]: print(list(zip(tuple1, tuple2)))                                                                              
[(1, 4), (2, 5), (3, 6)]

In [10]: print(tuple(zip(tuple1, tuple2)))                                                                            
((1, 4), (2, 5), (3, 6))

In [11]: print([[a, b,] for (a, b) in zip(myList, myTuple)])                                                          
[['a', 'd'], ['b', 'e'], ['c', 'f']]

9 Likes

It took that long for somebody to investigate. I’m anything but embarrassed.

6 Likes

I think my brain just became a tuple

2 Likes