Skip to content Skip to sidebar Skip to footer

List Of Squares In Python

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,

Solution 1:

Use list comprehension:

defsquares(n):
    L = [i*i for i inrange(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]

Solution 2:

By using list comprehension

l=[x*x for x in range(1,n+1)]

Solution 3:

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]

Solution 4:

Here is another approach :

defsquares(n):
    returnlist(map(lambda k:k**2, range(1,n+1)))

Solution 5:

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

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

this will give your desired output

Hope this answers your question.

Post a Comment for "List Of Squares In Python"