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
1,886 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,960 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
100,085 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
1,439 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,520 points
3,225 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