Katie
Katie

Reputation: 1

Modifying parameters through the function

I'm trying to figure out how I would go about getting the square_each list back without using return?

Here are the specifics: Write and test a function square_each(nums), where nums is a (Python) list of numbers. It modifies the list nums by squaring each entry and replacing its original value. You must modify the parameter, return will not be allowed!

def square_each(nums):
    for i in range(len(nums)):
        nums[i]= int(nums[i]) * int(nums[i])
    return nums

def sum_list(str_list):
    x = sum(str_list)
    return x

def to_numbers(str_list):
    for i in range(len(str_list)):
        str_list[i] = eval(str_list[i])
    return str_list

def main():
    file=open("numbers.txt").readline().split(" ")
    print(to_numbers(file))
    print(square_each(file))
    print(sum_list(file))

main()

Upvotes: 0

Views: 838

Answers (3)

pschill
pschill

Reputation: 5579

The function square_each that you posted already fulfills your conditions:

def square_each(nums):
    for i in range(len(nums)):
        nums[i] = int(nums[i]) * int(nums[i])

l = [1, 2, 3]
square_each(l)
print(l)  # output: [1, 4, 9]

Upvotes: 0

Vipin Chaudhary
Vipin Chaudhary

Reputation: 444

You have to declare nums in global scope

So do it like this

nums = [] # your array in global scope

def square_each():
    # Now you can use original nums
    global nums
    for i in range(len(nums)):
        nums[i]= int(nums[i]) * int(nums[i])

Upvotes: -1

Sanyam Khurana
Sanyam Khurana

Reputation: 1421

You can use list comprehension and play with how Python deals with objects. It is neither call by value, nor call by reference

def square_each(num_list):
    intermediate_list = [x**2 for x in num_list]
    num_list.clear()  # Removes all the elements of current list
    num_list.extend(intermediate_list)  # Adds processed elements to the original list

Here you need to modify the list in-place.

Note that it is better than using global or any other such stuff, since it prevents the introduction of other set of problems that may be introduced due to global keyword.

Upvotes: 1

Related Questions