+ 3
What are generators exactly and how does the memory reserved for them...?
4 Respostas
+ 3
Yathindra S. Yes, for example you want to create a list of numbers multiplied by itself from 0-9.
You might do it using list comprehension.
nums = [i * i for i in range(10)]
You can do the same thing using generator.
def num_generator(length):
for i in range(length):
yield i * i
nums = num_generator(10)
However, you cannot access the elements of generator by indexing. You can only iterate over it.
To really understand generators. You must first understand the concept of iterables and iterators.
+ 3
Generator functions behaves likes an iterator.
When you create a list, all of its elements are stored in memory. Generator functions yields only one element at a time. That means only one element is stored in memory. And that makes it more efficient in memory management.
+ 2
Hello Nadie,
So, if we want to create a list of 100 numbers, don't we need to store 100 values in it.. if we use generators...?
+ 2
Hello Nadie Fiind,
Thank you so much for your answer. I found it so useful. May others find this answer perfect.