- When compared with class level iterators, generators are very easy to use Improves memory utilization and performance.
- Generators are best suitable for reading data from large files.
- Generators work great for web scraping.
Performance – generator vs collections
Python
import random
import time
names = ['Ajay','Amit','Aman','Manish']
subjects = ['Python','Java','C']
def people_list(num_people):
results = []
for i in range(num_people):
person = {
'id':i,
'name': random.choice(names),
'subject':random.choice(subjects)
}
results.append(person)
return results
def people_generator(num_people):
for i in range(num_people):
person = {
'id':i,
'name': random.choice(names),
'major':random.choice(subjects)
}
yield person
t1 = time.localtime()
people = people_list(10000000)
t2 = time.localtime()
print('Took {}'.format(t2-t1))
t1 = time.localtime()
people = people_generator(10000000)
t2 = time.localtime()
print('Took {}'.format(t2-t1))
Output
Memory – generator vs collections
Normal collection
Python
l=[x*x for x in range(10000000000000000)]
print(l[0])
Output
- We will get MemoryError.
Generators
Python
g=(x*x for x in range(10000000000000000))
print(next(g))
Output
PowerShell
0
- We won’t get any MemoryError because the values won’t be stored at the beginning.
Ungraded Questions
Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!