Home » Python

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






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.