0

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.

3
Contributors
3
Replies
5
Views
5 Years
Discussion Span
Last Post by pyTony
Featured Replies
  • 1

    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 … Read More

0

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))

Edited by woooee: n/a

0

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

1

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()

Edited by pyTony: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.