List Comprehension vs Generator Expressions in Python
1 min read

List Comprehension vs Generator Expressions in Python

List Comprehension vs Generator Expressions in Python

A list comprehension does the same thing that a generator expression does, however there are some minute differences between these too.

Here's how we write list comprehension

[expression for item in list]

And here's how we write an expression generator

(expression for item in list)

Usage example of list comprehension and its output

animals = ["cat", "dog", "bat"]
animals = [animal.upper() for animal in animals]
print(animals)
Output: ['CAT', 'DOG', 'BAT']

Usage example of an expression generator and its output

animals = ["cat", "dog", "bat"]
animals = (animal.upper() for animal in animals)
print(animals)
Output: <generator object <genexpr> at 0x000002597768C570>

Notice that we don't get our output immediately when using an expression generator. This is because an expression generator does it lazily.

In the above example, in case of list comprehension, the names of all animals will be converted immediately.

animals = [animal.upper() for animal in animals]
for animal in animals:
    print(animal)

Output

CAT
DOG
BAT

Here's the order of above task in list comprehension

upper, upper, upper
output
output
output

Using an expression generator,

animals = (animal.upper() for animal in animals)
for animal in animals:
    print(animal)
CAT
DOG
BAT

Here's the order of above task in an expression generator

upper, output
upper, output
upper, output

In case of expression generator we are not applying the uppercase method to all the string at once but instead we are applying the function during iteration one by one.

Memory usage

A list comprehension takes much more memory than an expression generator when the no. of elements inside the list is huge.

Index Access

The items inside an expression generator is not index accessible however we can convert it to list using the list function and can access element by index.

Iterable

Both expression generator and list comprehension are iterable and produces the same output.

Enjoying these posts? Subscribe for more


Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×