12oad2016-08-28 17:27:29
12oad, 2016-08-28 17:27:29

2 questions on functions. Python?

def swap_columns(a, i, j):
    for k in range(n):
        a[k][i], a[k][j] = a[k][j], a[k][i]
    return a

I didn't declare " global a " -- why would the list items change globally?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Evgeny Kornachev, 2016-08-28

Lists in python are passed by reference. This means that passing a list to a function will change the passed list, rather than creating a "copy" within the function.
If you want to create a new list, then you need to pass a full (deep) copy of the original list to the function, or create such a copy inside the function and perform operations on it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question