0

When I switch to 'generator' instead of the classic list iteration ?

Please I spent a lot of time looking for the power of 'generators' in python but until now I still confused about the use case of it. Anyone here confronted an example that using generators is better than the classic lists.

6th Aug 2017, 1:23 PM
Mohamed Abdeljelil
Mohamed Abdeljelil - avatar
2 Antworten
0
Generators are just iterators. They are class objects in python that have their uses, like being used in a for loop or a comprehension list. They're technically simple functions built into python, which then return a list of items, one at a time. It does this till it reaches a yield statement, then it returns the value. You can easily see this in use by using a comprehension: alist = [x for x in range(10)] blist = (x for x in range(10)) print(type(alist)) print(type(blist)) # Output: alist: <class 'list'> blist: <class 'generator'> The alist generator first generated it's list, then returned the results into the list, one at a time. The blist generator - generated the numbers, but could not store any into the immutable tuple. So the generator object is still there, but the yield was not called. You can still extract them by using a for loop: for each in blist: print (each) Generators in python are there for your convenience. They are objects that are not only capable of iterating over values, but also storing them for later use. That's what primarily separates them. There's also a performance boost, I don't know the details of that. There's probably more uses than that, but I haven't gone that far personally. There is more technical babble about them, but that's out of my scope. Someone else can explain it better if they like.
6th Aug 2017, 1:45 PM
Sapphire
0
what is iteration
14th Jul 2018, 8:35 AM
adarsh pandey
adarsh pandey - avatar