+1 vote
in Programming Languages by (8.1k points)

When I try to unzip a zipped list of lists, Python gives the following error:

TypeError: 'zip' object is not subscriptable

Here is the line of code I am using:

labels = list(zip(*savedData[n])[0])

and my savedData is similar to : [[(1, 11), (2, 22), (3, 33)], [(4, 44), (5, 55), (6, 66)]]

1 Answer

0 votes
by (15.9k points)

It seems that you are using Python3 and hence your code is giving the error. In Python2, zip() returns a list, whereas, in Python3, it returns an object. So, you need to make the returned object a list and then you can apply 'unzip' on that. Check the following highlighted code.

>>> a=[1,2,3]
>>> b=[11,22,33]
>>> c=[4,5,6]
>>> d=[44,55,66]
>>> savedData=[[],[]]
>>> savedData[0]=zip(a,b)
>>> savedData[1]=zip(c,d)
>>> savedData
[<zip object at 0x7efc0951bf48>, <zip object at 0x7efc0951bf88>]
>>> x,y=zip(*list(savedData[1])) #convert savedData to a list before unzipping
>>> x
(4, 5, 6)
>>> y
(44, 55, 66)
>>> x,y=zip(*list(savedData[0]))
>>> x
(1, 2, 3)
>>> y
(11, 22, 33)
>>>

...