1

I need to write a function of the first n square numbers, The sequence of squares start with 1, 4, 9, 16, 25.

For example if the input is 16, the output will be

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256] 

This code is what I've tried, but its completely wrong. This code counts my number from 1 to 255. I have no idea what to fix

def squares(n):
    L = list(range(n**2))
    L = [num for num in L if num]
    return L
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
Matthew Lee
  • 69
  • 1
  • 1
  • 6

6 Answers6

3

Use list comprehension:

def squares(n):
    L = [i*i for i in range(1,n+1)]
    return L

print (squares(16))

output:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256]
ncica
  • 7,015
  • 1
  • 15
  • 37
2

By using list comprehension

l=[x*x for x in range(1,n+1)]
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
1

For this you can use a function, with a list comprehension inside it. What this does is it takes parameter n, and returns the square of every number up to and including n (because of the n+1 term in the range), by using the for-loop in the list comprehension.

def list_of_squares(n):
    return [i**2 for i in range(1,n+1)]

For example, print(list_of_squares(10)) will print the first 10 squares.

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Psychotechnopath
  • 2,471
  • 5
  • 26
  • 47
1
def squares(n):
       L = []
       for num in range(1,n+1):
           val = num*num 
           L.append(val)
       return L
print(squares(16))

output

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256]
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
1

Here is another approach :

def squares(n):
    return list(map(lambda k:k**2, range(1,n+1)))
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
1

Your main issue is that you used range wrongly, you used range on (n**2) instead of n. This means that you will get values from 1^2, to 16^2, with every integer in between. As you can see through previous answers by other people the did not use range. However if you do want to use it this should work

def squares(n):
   L = list(range(n+1))
   L = [num**2 for num in L if num]
   return L
print(squares(16))

this will give your desired output

Hope this answers your question.