Generator Expressions vs. List Comprehension

0 votes
What is the difference between Generator Expressions and List Comprehensions in Python?
Jul 15 in Python by Fata
• 1,000 points
20 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 by Wajiha
• 1,840 points

Related Questions In Python

+1 vote
2 answers

Difference between append vs. extend list methods in Python

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

answered 1 day ago in Python by germyrinn
• 180 points
167 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
• 160 points
30 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,350 points
85 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
123 views
0 votes
1 answer

List comprehension on a nested list - How to do it in Python?

Not sure what your desired output is, ...READ MORE

answered Nov 21, 2018 in Python by Nymeria
• 3,520 points
77 views
0 votes
1 answer

How to get the multiplication table of any number using list comprehension?

Hey @Neha, you can use something like ...READ MORE

answered Jul 8 in Python by Sakshi
28 views
0 votes
1 answer

Generators with plots

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

answered Jul 16 in Python by Wajiha
• 1,840 points
16 views
0 votes
0 answers

Produce infinite number stream?

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

Jul 16 by Fata
• 1,000 points
8 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 in Python by Wajiha
• 1,840 points
18 views
0 votes
1 answer

Difference between function and generator?

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

answered Jul 15 in Python by Wajiha
• 1,840 points
31 views