Python TypeError: 'generator' object is not subscriptable

August 10, 2019

Trying to access generators by index will trigger TypeError: 'generator' object is not subscriptable

def country_generator():
    yield 'Malaysia'
    yield 'Singapore'
    yield 'Japan'

countries = country_generator()

if countries:
    print(countries[0])

Convert generator to list

countries = list(countries)
if countries:
    print(countries[0])

Use next

country = next(countries, None)
if country:
    print(country)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.