braindead
braindead

Reputation: 97

python: using remove() to remove an element from list by value

I wrote a simple script as follows:

def  simplefunc(listofcolumns):
    mylist = listofcolumns  
    mylist.remove(1)

listofcolumns = [1,2,3,4,5,6]
simplefunc(listofcolumns)
print listofcolumns

The output I get is [2,3,4,5,6]. My question is, why is it not [1,2,3,4,5,6]? How can I do this

such that I get the answer [1,2,3,4,5,6]?

Upvotes: 1

Views: 123

Answers (3)

Erik Wennstrom
Erik Wennstrom

Reputation: 134

When you write mylist = listofcolumns, you aren't making a new list. You're just pointing the variable mylist at the same list that listofcolumns refers to. So any modification you make to mylist or listofcolumns is modifying that same original list. If you want to make a copy of a list so that you can modify it without messing with the original list, you can use the .copy() method, like so:

def  simplefunc(listofcolumns):
    mylist = listofcolumns.copy()  
    mylist.remove(1)

Or you can do like Kasra suggested and not pass the original list in the first place.

As was pointed out in the comments below, .copy() is new to Python 3. For older versions of Python, you can accomplish the same thing by making a slice of the whole list: def simplefunc(listofcolumns): mylist = listofcolumns[:] mylist.remove(1)

Upvotes: 1

Sakib Ahammed
Sakib Ahammed

Reputation: 2480

You passing this List by reference. when mylist = listofcolumns, all element address are copy in mylist. so when you change in mylist, it also change listofcolumns. But when you use mylist = listofcolumns[:] it's only copy elements. You can try this:

def  simplefunc(listofcolumns):
    mylist = listofcolumns[:] 
    mylist.remove(1)
    print listofcolumns
    print mylist

listofcolumns = [1,2,3,4,5,6]
simplefunc(listofcolumns)
print listofcolumns

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107287

Its because of that changing a mutable object argument in a function may impact the caller! and will change your object globally! for get ride of such behavior you can do one of the following ways :

  1. pass a copy of your list to function
  2. convert your mutable object to an immutable object and then pass.

So you can do :

listofcolumns = [1,2,3,4,5,6]
simplefunc(listofcolumns[:])

or you can convert your list to a tuple that is a immutable objectbut in your case as tuple object has no attribute remove you cant use the following way for your problem.:

listofcolumns = [1,2,3,4,5,6], 
simplefunc(tuple(listofcolumns))

Upvotes: 1

Related Questions