Write and test a function to meet this specification:

squareEach(nums) nums is a LIST of numbers. Modifies the list by squaring each entry.

``````def squareEach(nums):
for number in nums:
number = number ** 2
return number

def main():
nums = [3,4]
print(squareEach(nums))
main()``````

The output in this case is 9... I tried moving the return statement back one tab,
but then the output would be 16. I need it to print both 9 and 16.

## All 3 Replies

If you want to return the original list, then modify it's contents. If not, return a new list (you only return one number, not the entire list).

``````def square_each(nums):
for ctr in range(len(nums)):
nums[ctr] **= 2
return nums

def square_new_list(nums):
return_list = []
for num in nums:
return_list.append(num**2)
return return_list

#def main():

nums = [3,4]
print(square_each(nums))

nums = [3,4]
print(square_new_list(nums))``````

If you want to return the original list, then modify it's contents. If not, return a new list (you only return one number, not the entire list).

``````def square_each(nums):
for ctr in range(len(nums)):
nums[ctr] **= 2
return nums

def square_new_list(nums):
return_list = []
for num in nums:
return_list.append(num**2)
return return_list

#def main():

nums = [3,4]
print(square_each(nums))

nums = [3,4]
print(square_new_list(nums))``````

got it thanks a lot

If you meant the words you wrote in your first post and want the function to modify the list values you can do it like this with full slice at left and generator producing value for each element on right side. Then you do not return value, but you print the changed list:

``````def squareEach(nums):
# we can not assign to nums, but we can assign to each element of list
# by putting full slice to left side
nums[:]= (number ** 2 for number in nums)

def main():
nums = [3,4]
squareEach(nums)
print nums

main()``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.