In Python, you cannot access values inside a zip object using indexing syntax. The zip()
function takes iterables and aggregates them into a tuple. The resultant zip
object is an iterator of tuples. You can solve this error by converting the zip
object to a list object using the built-in list()
method. For example,
a = ("Jill", "Xavier", "Lucy") b = ("Chance", "Will", "Ken") x = list(zip(a, b)) first_pair = x[0]
This tutorial will go through the error in detail and how to solve it with code examples.
Table of contents
TypeError: ‘zip’ object is not subscriptable
Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type. The part “zip object” tells us the error concerns an illegal operation for the zip object returned by the zip method.
The part “is not subscriptable” tells us we cannot access an element of the zip object using the subscript operator, which is square brackets []
.
A subscriptable object is a container for other objects and implements the __getitem__()
method. Examples of subscriptable objects include strings, lists, tuples, and dictionaries.
We can check if an object implements the __getitem__()
method by listing its attributes with the dir
function. Let’s call the dir
function and pass a zip
object and a string object to see their attributes.
a = ("Jill", "Xavier", "Lucy") b = ("Chance", "Will", "Ken") x = zip(a, b) print(dir(x))
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
string = "Python" print(dir(string))
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
If you want to check if a specific attribute belongs to an object, you can check for membership using the in
operator.
a = ("Jill", "Xavier", "Lucy") b = ("Chance", "Will", "Ken") x = zip(a, b) # Check type of object print(type(x)) # Check membership of attribute print('__getitem__' in dir(x))
<class 'zip'> False
We can see that __getitem__
is not an attribute of the zip
class.
string = "Python" print(type(string)) print('__getitem__' in dir(string))
<class 'str'> True
We can see that __getitem__
is an attribute of the string object.
Example
Let’s look at an example of trying to index a zip
object. In the code below we will define two tuples, one containing the names of three fruits and the other containing the names of three vegetables.
a = ("Apple", "Mango", "Guava") b = ("Spinach", "Carrot", "Potato")
Next, we will call the zip
method to create an iterator of tuples where the item in each tuple are paired together in order.
x = zip(a, b)
Next, we will attempt to get the first tuple in the zip
object using the subscript operator []
.
first_fruit_veg = x[0] print(first_fruit_veg)
Let’s run the code to see what happens:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [27], in <cell line: 6>() 2 b = ("Spinach", "Carrot", "Potato") 4 x = zip(a, b) ----> 6 first_fruit_veg = x[0] 8 print(first_fruit_veg) TypeError: 'zip' object is not subscriptable
The error occurs because we are trying to access the first tuple using indexing, which is not possible with zip
objects.
Solution
We can solve this error by converting the zip
object to a list using the built-in list()
method. Lists are subscriptable objects.
Let’s look at the revised code:
a = ("Apple", "Mango", "Guava") b = ("Spinach", "Carrot", "Potato") x = list(zip(a, b)) first_fruit_veg = x[0] print(first_fruit_veg)
Let’s run the code to get the first tuple:
('Apple', 'Spinach')
Summary
Congratulations on reading to the end of this tutorial!
For further reading on AttributeErrors, go to the article:
How to Solve Python TypeError: ‘dict_items’ object is not subscriptable
To learn more about Python for data science and machine learning, you can go to the online courses page on Python for the most comprehensive courses.
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.