Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mutate a list with a function in python?

Here's a pseudocode I've written describing my problem:-

func(s):
   #returns a value of s

x = a list of strings
print func(x)
print x #these two should give the SAME output

When I print the value of x in the end, I want it to be the one returned by func(x). Can I do something like this only by editing the function (and without setting x = func(x))

like image 768
Ritvik Sharma Avatar asked Jul 11 '15 17:07

Ritvik Sharma


People also ask

Can list be mutated in Python?

Mutable and Immutable Data Types in PythonMutability in Python doesn't just apply to lists and integers, but other data types as well. We just focused on lists in this article to keep things programmatic.

What is a mutating function in Python?

Mutating methods are ones that change the object after the method has been used. Non-mutating methods do not change the object after the method has been used. The count and index methods are both non-mutating. Count returns the number of occurrences of the argument given but does not change the original string or list.

Can lists be mutated?

Lists are ordered collections of other objects. And lists are mutable.

How do you make a list immutable in Python?

Instead of tuple, you can use frozenset. frozenset creates an immutable set. you can use list as member of frozenset and access every element of list inside frozenset using single for loop. frozenset requires its set members to be hashable, which a list is not.


2 Answers

That's already how it behaves, the function can mutate the list

>>> l = ['a', 'b', 'c'] # your list of strings
>>> def add_something(x): x.append('d')
...
>>> add_something(l)
>>> l
['a', 'b', 'c', 'd']

Note however that you cannot mutate the original list in this manner

def modify(x):
    x = ['something']

(The above will assign x but not the original list l)

If you want to place a new list in your list, you'll need something like:

def modify(x):
    x[:] = ['something'] 
like image 181
bakkal Avatar answered Oct 22 '22 15:10

bakkal


func(s):
   s[:] = whatever after mutating
   return s

x = a list of strings
print func(x)
print x

You don't actually need to return anything:

def func(s):
    s[:] = [1,2,3]

x = [1,2]
print func(x)
print x # -> [1,2,3]

It all depends on what you are actually doing, appending or any direct mutation of the list will be reflected outside the function as you are actually changing the original object/list passed in. If you were doing something that created a new object and you wanted the changes reflected in the list passed in setting s[:] =.. will change the original list.

like image 37
Padraic Cunningham Avatar answered Oct 22 '22 14:10

Padraic Cunningham