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?
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With