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)
)
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.
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.
Lists are ordered collections of other objects. And lists are mutable.
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.
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']
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.
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