Jan-02-2021, 01:00 AM
I'm new to generators. Reuven Lerner describes them as "lazy lists"
This one assigns the letters of a string to alist a prescribed number of times.
But alist has no values.
Is this because the generator only makes the values when called by print(list(alist))??
What exactly is alist here? Is it like a function that can be called?
What is the difference between a generator and a list comprehension??
Maybe, the generator uses less memory, only works on demand??
This one assigns the letters of a string to alist a prescribed number of times.
But alist has no values.
Is this because the generator only makes the values when called by print(list(alist))??
What exactly is alist here? Is it like a function that can be called?
#! /usr/bin/python3 # simple generator myString = 'generator' n = len(myString) max_times = 12 alist = (myString[x % n] for x in range(max_times)) # alist returns <generator object <genexpr> at 0x7fb489ca4ba0> in Idle # print(alist) returns <generator object <genexpr> at 0x7fb489ca4ba0> in Idle print(list(alist)) # returns ['g', 'e', 'n', 'e', 'r', 'a', 't', 'o', 'r', 'g', 'e', 'n']If I use a list comprehension, I get a list:
alist2 = [myString[x%n] for x in range(max_times)]Enter alist2 in Idle and I immediately get:
Quote:>>> alist2
['g', 'e', 'n', 'e', 'r', 'a', 't', 'o', 'r', 'g', 'e', 'n']
>>>
What is the difference between a generator and a list comprehension??
Maybe, the generator uses less memory, only works on demand??