Reputation: 19
I need to accept a list of numbers and make that numbers squared. Based on this. I thought that the code I was writing was correct but it didn't show any output.
Can you guys help me figure out what's wrong?
def square(num_list):
Accepts a list of numbers, and returns a list of the same numbers squared.
e.g. [1, 2, 3] -> [1, 4, 9]
"""
return squared_list
#MYCODE
def squared(list):
squared_list = [ ]
for i in squared_list:
squared_list.append(i ** 2)
return squared_list
Upvotes: 0
Views: 71
Reputation: 11228
you can use list comprehension
def square(input_list):
square_list =[ number**2 for number in input_list]
return square_list
Upvotes: 2
Reputation: 5459
for i in squared_list:
^That's your problem, you go through the empty list, not the one with numbers.
So it should be:
def squared(list):
squared_list = [ ]
for i in list: # changed here
squared_list.append(i ** 2)
return squared_list
Also, I'd recommend not using the name list
- it shadows the buildin class name. It's ok in a function (you shadow it only in that function) but still a bad practice.
There's also a much shorter version using list comprehension: return [i**2 for i in list]
Upvotes: 0
Reputation: 7206
def squared(list):
squared_list = []
for i in list: #<---- you are itterating over empty list squared_list
squared_list.append(i**2)
return squared_list
print (squared([1,2,3]))
output:
[1, 4, 9]
Upvotes: 2