TypeError: 'zip' object is not subscriptable in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: 'zip' object is not subscriptable in Python #

The Python "TypeError: 'zip' object is not subscriptable" occurs when we try to access a zip object at a specific index. To solve the error, convert the zip object to a list, before accessing an index, e.g. list(zip(list_1, list_2))[0].

typeerror zip object is not subscriptable

Here is an example of how the error occurs.

main.py
list_1 = [1, 2, 3] list_2 = ['a', 'b', 'c'] result = zip(list_1, list_2) print(type(result)) # 👉️ <class 'zip'> # ⛔️ TypeError: 'zip' object is not subscriptable print(result[0])

Notice that the zip function returns a zip object, not a list.

To solve the error, pass the zip object to the list constructor to convert it to a list before accessing a list item at a specific index.

main.py
list_1 = [1, 2, 3] list_2 = ['a', 'b', 'c'] # ✅ convert to list result = list(zip(list_1, list_2)) # 👇️ [(1, 'a'), (2, 'b'), (3, 'c')] print(result) print(result[0]) # 👉️ (1, 'a') print(result[1]) # 👉️ (2, 'b')

The zip function iterates over several iterables in parallel and produces tuples with an item from each iterable.

The zip function returns an iterator of tuples.

Alternatively, you can pass the iterator to the next() function to retrieve the next item.

main.py
list_1 = [1, 2, 3] list_2 = ['a', 'b', 'c'] result = zip(list_1, list_2) print(next(result)) # 👉️ (1, 'a') print(next(result)) # 👉️ (2, 'b') print(next(result)) # 👉️ (3, 'c')

Note that if you try to access a list index that is out of bounds, you would get an error. You can use a try/except statement if you need to handle that.

main.py
list_1 = [1, 2, 3] list_2 = ['a', 'b', 'c'] # ✅ convert to list result = list(zip(list_1, list_2)) try: print(result[100]) except IndexError: print('index out of bounds') # 👉️ this runs

The example catches the IndexError that is thrown if the index is out of bounds.

The list constructor takes an iterable, such as a zip object, and converts it to a list.

The list constructor builds a list whose items are the same and in the same order as the iterable's items.

The list constructor takes an iterable that may be a sequence, a container that supports iteration or an iterator object.

Conclusion #

The Python "TypeError: 'zip' object is not subscriptable" occurs when we try to access a zip object at a specific index. To solve the error, convert the zip object to a list, before accessing an index, e.g. list(zip(list_1, list_2))[0].

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.