Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list of square powers of numbers in range using generator

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.

like image 528
marks34 Avatar asked Jan 08 '11 23:01

marks34


3 Answers

You'd be better off using list comprehension:

basic = [x*x for x in range(11)]
like image 176
SilentGhost Avatar answered Nov 15 '22 09:11

SilentGhost


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]
>>>
like image 38
John Machin Avatar answered Nov 15 '22 11:11

John Machin


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]
like image 40
Mark Tolonen Avatar answered Nov 15 '22 11:11

Mark Tolonen