Junior — Middle
How can you access an element by its position in a generator in Python?
sobes.tech AI
Answer from AI
Generators in Python do not support direct index access because they produce items one at a time and do not store them in memory. To get an element by position, you can:
- Use the
itertools.islicefunction to skip the first N elements:
import itertools
def get_element_at(gen, index):
return next(itertools.islice(gen, index, index+1))
# example
gen = (x*x for x in range(10))
print(get_element_at(gen, 3)) # will output 9
- Convert the generator to a list (if memory allows):
gen = (x*x for x in range(10))
lst = list(gen)
print(lst[3]) # 9
The first method is more efficient when working with large or infinite generators.