Generator Expressions vs List Comprehension

0 votes
What is the difference between Generator Expressions and List Comprehensions in Python?
Jul 15, 2019 in Python by Fata
• 1,050 points
358 views

1 answer to this question.

0 votes

Generator expression resemble list comprehensions. List comprehensions are specified within [] brackets and they produce the complete list of items at once. On the other hand, generator expressions, which are specified using () brackets, return the same items but one at a time. 

EXAMPLE:

a=range(6)

print("List Comprehension", end=':')

b=[x+2 for x in a]

print(b)

print("Generator expression", end=':n')

c=(x+2 for x in a)

print(c)

for y in c:

    print(y)

OUTPUT:

List Comprehension:[2, 3, 4, 5, 6, 7]

Generator expression:

<generator object <genexpr> at 0x0000016362944480>

2
3
4
5
6

answered Jul 15, 2019 by Wajiha
• 1,950 points

Related Questions In Python

+1 vote
3 answers

Difference between append vs. extend list methods in Python

Python append() method adds an element to ...READ MORE

answered Aug 21, 2019 in Python by germyrinn
• 240 points
67,729 views
0 votes
1 answer

Normal Python code equivalent to given list comprehension

You can try this code list1=[] for i in ...READ MORE

answered Jun 8, 2018 in Python by jain12
• 170 points
198 views
0 votes
1 answer

Difference between append vs. extend list methods in Python

append: Appends object at the end. x = ...READ MORE

answered Aug 8, 2018 in Python by bug_seeker
• 15,550 points
1,254 views
0 votes
1 answer

Using list comprehension how to call list of function

For the class method when used as ...READ MORE

answered Nov 14, 2018 in Python by Theodor
• 740 points
2,500 views
0 votes
1 answer

Generators with plots

Yes, you can. I tried doing it ...READ MORE

answered Jul 16, 2019 in Python by Wajiha
• 1,950 points
185 views
0 votes
0 answers

Produce infinite number stream?

Is it possible to produce an infinite ...READ MORE

Jul 16, 2019 by Fata
• 1,050 points
96 views
0 votes
1 answer

How to convert one list into generator?

Hi@akhtar, Say, you have one list A. Now convert ...READ MORE

answered Apr 23, 2020 in Python by MD
• 95,320 points
929 views
0 votes
1 answer

Is there anyway to get the total count of times of a Generator?

Generators are originally created to return an ...READ MORE

answered Nov 6, 2020 in Python by Gitika
• 65,970 points
80 views
0 votes
1 answer

Slicing a list using a variable, in Python

Yes its possible. Use the following piece ...READ MORE

answered Jul 2, 2019 in Python by Wajiha
• 1,950 points
606 views
0 votes
1 answer

Difference between function and generator?

Normal Functions vs Generator Functions: Generators in Python ...READ MORE

answered Jul 15, 2019 in Python by Wajiha
• 1,950 points
2,708 views