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?
Asked
Active
Viewed 9.0k times
235

Karl Knechtel
- 62,466
- 11
- 102
- 153

user17151
- 2,607
- 3
- 18
- 13
1 Answers
464
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)]

Mike Corcoran
- 14,072
- 4
- 37
- 49
-
54In other words `lambda x: zip(*x)` is self-inverse. – jwg May 24 '17 at 16:38
-
4This doesn't seem to be working: `l1 = [1,2,3]`, `l2 = [4,5,6]`; if I call `a,b = zip(*zip(l1,l2))`, then `a = (1,2,3) != l1 = [1,2,3]` (because [tuple != list](https://stackoverflow.com/questions/626759/whats-the-difference-between-lists-and-tuples)) – fosco Aug 29 '18 at 18:28
-
3@FoscoLoregian `a,b = map(list, zip(*zip(l1,l2)))` – JLDiaz Oct 26 '18 at 10:25
-
1See also https://stackoverflow.com/a/6473724/791430 – Omer Tuchfeld Jul 01 '19 at 12:02
-
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: https://stackoverflow.com/questions/714475/what-is-a-maximum-number-of-arguments-in-a-python-function – John Smith Optional May 28 '20 at 00:05
-
1No, because the limit of 255 doesn't apply when you expand args using *; see Chris Colbert's answer to https://stackoverflow.com/questions/714475/what-is-a-maximum-number-of-arguments-in-a-python-function – Adam Selker Jun 08 '21 at 22:08
-
I might mention the fact that you can look at the `zip` function and notice that it is almost naturally the inverse of itself – SomethingSomething Jul 26 '21 at 12:06
-
2having an unzip function would have been nice (even if just an alias of zip...) – daruma Nov 08 '21 at 05:47
-
4This answer is not quite complete, if you start with two empty lists you will not get them back. – mueslo Feb 18 '22 at 17:47
-
I thought that this method would work slowly but it actually worked better than all the other ways I imagined. Why is this so fast? – Fırat Kıyak Jul 01 '22 at 13:37