Python TypeError: 'generator' object is not subscriptable

Aug 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)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.