Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a list while retaining the original

Tags:

python

list

So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?

Example:

def burninate(b):
    c = []
    for i in range(3):
        c.append(b.pop())
    return c

a = range(6)
d = burninate(a)
print a, d

Output: [0, 1, 2] [5, 4, 3]
Desired output: [0, 1, 2, 3, 4, 5] [5, 4, 3]

Thanks!

like image 652
James Avatar asked Oct 22 '08 22:10

James


People also ask

Does list retain order python?

One of the chief characteristics of a list is that it is ordered. The order of the elements in a list is an intrinsic property of that list and does not change, unless the list itself is modified. (The same is true of tuples, except of course they can't be modified.)

Is Python list sorted by default?

The sort() method sorts the list ascending by default. You can also make a function to decide the sorting criteria(s).

Does list have order?

List is an Ordered Collection while Set is an unordered collection. List maintains insertion order of elements, means any element which is inserted before will go on lower index than any element which is inserted after.


2 Answers

As other answers have suggested, you can provide your function with a copy of the list.

As an alternative, your function could take a copy of the argument:

def burninate(b):
    c = []
    b = list(b)
    for i in range(3):
        c.append(b.pop())
    return c

Basically, you need to be clear in your mind (and in your documentation) whether your function will change its arguments. In my opinion, functions that return computed values should not change their arguments, and functions that change their arguments should not return anything. See python's [].sort(), [].extend(), {}.update(), etc. for examples. Obviously there are exceptions (like .pop()).

Also, depending on your particular case, you could rewrite the function to avoid using pop() or other functions that modify the argument. e.g.

def burninante(b):
    return b[:-4:-1]   # return the last three elements in reverse order
like image 88
John Fouhy Avatar answered Nov 09 '22 15:11

John Fouhy


You can call burninate() with a copy of the list like this:

d = burninate(a[:])

or,

d = burninate(list(a))

The other alternative is to make a copy of the list in your method:

def burninate(b):
    c=[]
    b=b[:]
    for i in range(3):
        c.append(b.pop())
    return c

>>> a = range(6)
>>> b = burninate(a)
>>> print a, b
>>> [0, 1, 2, 3, 4, 5] [5, 4, 3]
like image 45
mhawke Avatar answered Nov 09 '22 13:11

mhawke