I'd like to rewrite this part of code using generator :
basic = []
for x in range(0,11):
basic.append(x**2)
How can I do this ? Tried :
basic.append(x**2 for x in range(0,11))
but it raises syntax error in x**2
part.
You'd be better off using list comprehension:
basic = [x*x for x in range(11)]
You are mistaken; your code doesn't produce a syntax error, it just does the wrong thing:
>>> basic = []
>>> basic.append(x**2 for x in range(0,11))
>>> basic
[<generator object <genexpr> at 0x01E9AD78>]
>>>
If you must use a generator:
>>> basic = list(x**2 for x in range(0,11))
>>> basic
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>
It's simpler to use a list comprehension:
>>> basic = [x**2 for x in range(0,11)]
>>> basic
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>
Use extend
not append
.
>>> basic=[]
>>> basic.extend(x**2 for x in range(11))
>>> basic
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Better yet:
>>> basic = [x**2 for x in range(11)]
>>> basic
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With