How to Solve Python TypeError: ‘zip’ object is not subscriptable

by | Programming, Python, Tips

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.


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!

Research Scientist at Moogsoft | + posts

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!

Follow the Research Scientist Pod on Social media!