How do I save the output of a Python generator into memory?

Question:

This question probably has a straightforward answer, but I’m not finding it. I’m working with the Calendar class in Lib/calendar.py and there are several methods associated with that class that generate everything from date objects to tuples with year, month, day as integers, etc. The one example below generates weekday index integers 0 – 6:

from calendar import Calendar

CurrentYear = Calendar()
iter1 = CurrentYear.iterweekdays()
for i in iter1:
    print(i)

# 0
# 1
# 2
# 3
# 4
# 5
# 6

iter1 is an iterator that I can use to generate an index of weekdays without a problem. Of course, once generated, there’s nothing more to print if I run the loop again:

for I in iter1:
    print(i)

# no output

The documentation talks about using iterators quite a bit, but it’s usually alongside iterables already defined in the code that can be iterated over. But what if I don’t have the iterable already defined? How do I get the output of the generator into, say, a list container in memory so I can work with that list?

One thing I tried was this:

CurrentYear = Calendar()
wkday_list = []
iter1 = CurrentYear.iterweekdays()
for i in iter1:
    wkday_list[i] = iter1[i]

But, not knowing too much about iterators, I got this error:

TypeError: 'builtin_function_or_method' object is not subscriptable

Hopefully, it’s clear what I’m trying to do from these snippets. Is there a simple solution I can use to save output into memory that is generated by an iterator?

Asked By: Br. Brendan

||

Answers:

i is the value you want to save; you can write

wkday_list = []
for i in iter1:
    wkday_list.append(i)

or simply

wkday_list = list(iter1)

list itself will iterate over the iterator for your and build a list from the elements it gets back.

Answered By: chepner

You are using iter[i] instead of inter1[i]

Plus, you add an element to a list using the append() method, instead of wkday_list[i] as wkday_list has the length of 0 and using wkday_list[1] per say will break an outOfIndex error.

My approach :

from calendar import Calendar

CurrentYear = Calendar()
wkday_list = []
iter1 = CurrentYear.iterweekdays()
for i in iter1:
    wkday_list.append(i)

print(wkday_list)
Answered By: Mohamed Mahdi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.