What is the difference between generator expression and list comprehension?
Generatr expression doubt
Hello @vatsal50, see the difference:
List Comprehension:
sq = [ x**2 for x in range(1,11)]
print(sq)
# This is the list comprehension and here the output will be the list of the squares of numbers from 1 to 10.
## Output
## [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Generators in python: (Generator expression)
sq = ( x**2 for x in range(1,11))
# See the type of enclosing brackets we have used and now returning sq will return the generator
print(sq)
# <generator object <genexpr> at 0x7f3c4cd8c7b0> # This I have taken from my system and this is showing the address at which the generator is present.
# This is the generator expression and this works as an iterator so we need to use the next(sq) to get the values like,
print(next(sq))
print(next(sq))
print(next(sq))
print(next(sq))
print(next(sq))
print(next(sq))
print(next(sq))
print(next(sq))
print(next(sq))
print(next(sq))
print(next(sq))
## Output
## 1
## 4
## 9
## 16
## 25
## 36
## 49
## 64
## 81
## 100
## Traceback (most recent call last):
## File "<stdin>", line 1, in <module>
## StopIteration
# And you can see if we use the next(sq) more than 10 times (the range we are considering 1 to 11) then it will stop the iteration because we have initialised the iterator for range(1,11)
I hope the differences are clear to you. Pls, feel free to ask if there is any confusion.
And pls mark it as resolve if it is clear to you.
Thanks
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.