You've successfully subscribed to The Poor Coder | Hackerrank Solutions
Great! Next, complete checkout for full access to The Poor Coder | Hackerrank Solutions
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
List Comprehension vs Generator Expressions in Python

List Comprehension vs Generator Expressions in Python

Beeze Aal
Beeze Aal

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.