+ 8

Where I can use generator data in python?

How to use generator in our daily life

12th Jul 2019, 12:43 PM
Ashish Yadav
Ashish Yadav - avatar
4 Réponses
+ 1
First of all, there are two types of generators in python (generator expressions and generator functions), i am guessing that you are referring to generator expressions: So if you want to use an object(e.g. list) once in your code, then using generators is much memory efficient, because it is destroyed from memory once it is consumed. For exemple: nums = [2, 3, 4, 5, 6] evens = (i for i in nums if i % 2 == 0) # evens is a generator expression. # type(evens) to verify this. Print(sum(list(evens))) # here the list() function will iterate over evens by calling next() on it. # this will print out the sum of all numbers in evens Now if you want to use evens once again, you can't because it is already consumed by the list() built-in function. So to summarize this, it is preferable to use generators only when you need an object once in your code. I hope this can help in any possible way...
7th Oct 2020, 2:03 PM
QTWizard
+ 2
I think there is just 2 ways. 1: You iterate through it using for loop. 2: You convert it to an iterable, such as list or tuple.
12th Jul 2019, 1:46 PM
Seb TheS
Seb TheS - avatar
+ 1
A generator is a handy tool when you want to iterate over something when you don't have enough memory to save all this data at once, in a list for example, and then iterating over the list. For example, if you want to load images, let's say 8 images at a time, but the images are so large that the memory can't handle them, then using a generator is a pretty good idea. 😉
25th Jul 2019, 7:41 AM
Goodbye World 🇱🇧
Goodbye World 🇱🇧 - avatar
+ 1
You can use infinite generators when you don't know upfront how many elements you are going to need. https://code.sololearn.com/cLC0Ya2wj7Aq/?ref=app
25th Jul 2019, 10:27 AM
Tibor Santa
Tibor Santa - avatar