Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generator vs. list comprehension

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?

like image 930
myacobucci Avatar asked Nov 12 '13 15:11

myacobucci


People also ask

Which is faster list comprehension or generator expression?

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.

When should you use a generator instead of a list?

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.

What is a generator comprehension?

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.

What is the difference between list and list comprehension?

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.


1 Answers

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)
like image 119
Thomas Orozco Avatar answered Sep 30 '22 15:09

Thomas Orozco