I've used the zip
function from the Numpy library to sort tuples and now I have a list containing all the tuples. I had since modified that list and now I would like to restore the tuples so I can use my data. How can I do this?
1 Answer
lst1, lst2 = zip(*zipped_list)
should give you the unzipped list.
*zipped_list
unpacks the zipped_list object. it then passes all the tuples from the zipped_list object to zip, which just packs them back up as they were when you passed them in.
so if:
a = [1,2,3]
b = [4,5,6]
then zipped_list = zip(a,b)
gives you:
[(1,4), (2,5), (3,6)]
and *zipped_list
gives you back
(1,4), (2,5), (3,6)
zipping that with zip(*zipped_list)
gives you back the two collections:
[(1, 2, 3), (4, 5, 6)]
-
51
-
4This doesn't seem to be working:
l1 = [1,2,3]
,l2 = [4,5,6]
; if I calla,b = zip(*zip(l1,l2))
, thena = (1,2,3) != l1 = [1,2,3]
(because tuple != list)– foscoAug 29, 2018 at 18:28 -
3
-
2Wouldn't it fail for Python version 3.6 and older as soon as your list of zipped tuples contains more than 255 items ? (because of the maximum numbers of arguments that can be passed to a function) See: stackoverflow.com/questions/714475/… May 28, 2020 at 0:05
-
2having an unzip function would have been nice (even if just an alias of zip...)– darumaNov 8, 2021 at 5:47