Scope of variables: Python

What difference does it make when the empty list is created inside or outside the function definition?

Q. Create a function named exponents() that takes two lists as parameters named bases and powers . Return a new list containing every number in bases raised to every number in powers .
Code:
def exponents(bases,powers):
new_list=
for i in bases:
for j in powers:
new_list.append(i**j)
return new_list

print(exponents([2, 3, 4], [1, 2, 3]))

To preserve code formatting in forum posts, see: [How to] Format code in posts

Your code:

def exponents(bases,powers):
    new_list= []
    for i in bases:
        for j in powers:
            new_list.append(i**j)
    return new_list

Let’s call your function twice (or more):

print(exponents([2, 3, 4], [1, 2, 3]))
print(exponents([2, 3, 4], [1, 2, 3]))

#
# Output:
#
[2, 4, 8, 3, 9, 27, 4, 16, 64]
[2, 4, 8, 3, 9, 27, 4, 16, 64]

Now, move the empty list outside the function,

new_list = []
def exponents(bases,powers):
    for i in bases:
        for j in powers:
            new_list.append(i**j)
    return new_list

print(exponents([2, 3, 4], [1, 2, 3]))
print(exponents([2, 3, 4], [1, 2, 3]))

# Output:
[2, 4, 8, 3, 9, 27, 4, 16, 64]
[2, 4, 8, 3, 9, 27, 4, 16, 64, 2, 4, 8, 3, 9, 27, 4, 16, 64]

Thank you for pointing out the difference in outputs!
May I know the explanation behind why the iteration changes in both cases?

In the first version, new_list is being declared and initialized as an empty list inside the exponents function. Each time the exponents function is called, an empty list is created. Elements are appended to the list and the finally, the list is returned. If a fresh function call is made, another empty list is created. After the elements have been appended, the list is returned.

In the second version, new_list is being declared and initialized as an empty list outside and before the exponents function. This only happens once. When a function call is made to the exponents function, elements are appended to new_list and the list is then returned. If a fresh function call is made, new_list in no longer empty. It already holds the elements from the last function call. So the fresh function call will end up appending to the already existing list.

1 Like

Thank you, it was helpful