List Comprehension vs Generators Expression in Python

Python | List comprehension vs generators expression: Here, we are going to learn about the list comprehension and generators expression, and differences between of them.
Submitted by Bipin Kumar, on December 02, 2019

The list is a collection of different types of elements and there are many ways of creating a list in Python.

List Comprehension

List comprehension is one of the best ways of creating the list in one line of Python code. It is used to save a lot of time in creating the list.

Let's take an example for a better understanding of the list comprehension that calculates the square of numbers up to 10. First, we try to do it by using the for loop and after this, we will do it by list comprehension in Python.

By using the for loop:

List_of_square=[]

for j in range(1,11):
    s=j**2
    List_of_square.append(s)

print('List of square:',List_of_square)

Output

List of square: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Now, we do it by List comprehension,

List_of_square=[j**2 for j in range(1,11)]
print('List of square:',List_of_square)

Output

List of square: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

As we have seen that the multiple lines of code of for loop gets condensed into one line of code in the list comprehension and also saves the execution time.

Generator Expression

A generator expression is slightly similar to list comprehension but to get the output of generators expression we have to iterate over it. It is one of the best ways to use less memory for solving the same problem that takes more memory in the list compression. Here, a round bracket is used instead of taking output in the form of the list. Let’s look at an example for a better understanding of generator expression that will calculate the square of even numbers up to 20.

Program:

generators_expression=(j**2 for j in range(1,21) if j%2==0)
print('square of even number:')
for j in generators_expression:
    print(j, end=' ')

Output

square of even number:
4 16 36 64 100 144 196 256 324 400

Python Tutorial

 
 



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.