Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace an object in python

Tags:

python

Given the following example code:

def myfunc(item):
  if item == 2:
    item = 1

mylist = [1,2,3]
for i in mylist:
  myfunc(i)
print(mylist) # output is [1, 2, 3]
# desired output is [1, 1, 3]

I would like to have a function that is called for some or all elements of a list. This function should be able to alter these elements.

What would be the the cleanest solution for this problem?

like image 368
Fabian Henze Avatar asked Aug 31 '26 21:08

Fabian Henze


2 Answers

If you don't need the list to be modified in-place, you can create a new list with the new values. To this end, your functions should simply return the new value:

def myfunc(item):
    if item == 2:
        return 1
    return item

Then you can use map() or a list comprehension to construct the new list:

mylist = [1, 2, 3]
print map(myfunc, mylist)
like image 163
Sven Marnach Avatar answered Sep 02 '26 12:09

Sven Marnach


If you want to modify in-place your list you need to work with its indexes.

Something like:

for i,elm in enumerate(mylist):
    mylist[i] = myfunc(elm)

With a myfunc that looks like:

def myfunc(item):
    if item == 2:
        return 1
    else:
        return item

With this function you wouldn't actually need a function at all, but I hope you got my point :)


Expanding a bit Sven's comment, you could use list-slicing + map():

mylist[:] = map(myfunc, mylist)

I actually prefer this one than to use enumerate(). And since you seem to be on Python 3 this wouldn't even build a temporary list.

A generator-expression would work too! I wouldn't use it in some real code, because to me looks less readable, but it might me an interesting example:

>>> mylist = [0, 1, 2, 3, 4]
>>> mylist[:] = (x == 2 and 1 or x for x in mylist)
>>> mylist
[0, 1, 1, 3, 4]

Edit: What I thought about the non building of a temp list (for map() and for the generator-expressions) turned out to be false: see Sven's comment or his explanation from this other answer.

like image 21
Rik Poggi Avatar answered Sep 02 '26 11:09

Rik Poggi