How access element at an index of generator in python?

1.3k views Asked by At

I am new to python & facing issue while accessing second element of iterateable returned by function from lib pyyaml, yaml.load_all, below is code:

import os
import yaml
file = "abc.yaml"
stream = open(file)
docs = yaml.load_all(stream)
print docs[1]

output I am getting is

TypeError: 'NoneType' object has no attribute '__getitem__'

yaml is python lib for handling yaml format, yaml.load_all is explained here

2

There are 2 answers

0
Dima Tisnek On

If you only need that one document, then this should do:

docs = yaml.load_all(...)
next(docs)  # skip docs[0]
mydoc = next(docs)
0
bruno desthuilliers On

The error message you mention (TypeError: 'NoneType' object has no attribute '__getitem__') does not come from docs being a generator but from docs being None.

But anyway, to answer your question: you cannot "access element at an index in a generator", because generator are not subscriptable - the whole point of generators is to generate values on the fly. If you really need a subscriptable sequence, the simplest way is to build a list from your generator, ie:

docs = list(yaml.load_all(stream))

Now beware that you'd rather not do this unless you know for sure that 1. your generator is not infinite (generators can be infinite and some are) and 2. the list will fit in memory.

NB : I use the word "generator" here but it applies to iterators in general.