I have something, when run as a list comprehension, runs fine.
It looks like,
[myClass().Function(things) for things in biggerThing]
Function
is a method, and it builds a list. The method itself doesn't return anything, but lists get manipulated within.
Now when I change it to a generator ,
(myClass().Function(things) for things in biggerThing)
It doesn't manipulate the data like I would expect it to. In fact, it doesn't seem to manipulate it at all.
What is the functional difference between a list comprehension and a generator?
List comprehensions are usually faster than generator expressions as generator expressions create another layer of overhead to store references for the iterator. However, the performance difference is often quite small.
The generator yields one item at a time — thus it is more memory efficient than a list. For example, when you want to iterate over a list, Python reserves memory for the whole list. A generator won't keep the whole sequence in memory, and will only “generate” the next element of the sequence on demand.
A generator comprehension is a single-line specification for defining a generator in Python. It is absolutely essential to learn this syntax in order to write simple and readable code. Note: Generator comprehensions are not the only method for defining generators in Python.
The for loop is a common way to iterate through a list. List comprehension, on the other hand, is a more efficient way to iterate through a list because it requires fewer lines of code. List comprehension requires less computation power than a for loop because it takes up less space and code.
Generators are evaluated on the fly, as they are consumed. So if you never iterate over a generator, its elements are never evaluated.
So, if you did:
for _ in (myClass().Function(things) for things in biggerThing):
pass
Function
would run.
Now, your intent really isn't clear here.
Instead, consider using map
:
map(myClass().Function, biggerThing)
Note that this will always use the same instance of MyClass
If that's a problem, then do:
for things in BiggerThing:
myClass().Function(things)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With