mutate dictionary or list
deets at web.de
deets at web.de
Tue Sep 7 16:12:00 CEST 2010
Baba <raoulbia at gmail.com> writes:
> I am working on an exercise which requires me to write a funtion that
> will check if a given word can be found in a given dictionary (the
> def is_valid_word(word, hand, word_list):
> Returns True if word is in the word_list and is entirely
> composed of letters in the hand. Otherwise, returns False.
> Does not mutate hand or word_list."""
> I don't understand this part: Does not mutate hand or word_list
> I tried to google "python mutate list input" but to no avail
> It would be great if someone could give me a brief explanantion of the
> mutation concept.
Objects can be mutable or immutable. For example, in Python, integers,
strings, floats and tuples are immutable. That means that you can't
change their value.
Mutable objects OTOH can be changed. For example, a list is mutable:
l = ["foo"]
l.append("bar") # mutating method
print l #-> ['foo', 'bar']
That's all there is to it. So for the example at hand, don't use
anything that mutates the passed arguments. E.g, if word_list really is
a list, and for faster lookup of "word", you want to sort it, you are
not allowed to do this:
word_list.sort() # mutating!!
Instead, you need to do
new_word_list = sorted(word_list) # creates a *copy* of word_list,
which is sorted.
Actually, you can also try & use the module copy's "deepcopy"-function
to ensure that you don't mutate the passed objects.
Please not that this is *not* a mutating operation:
l = [1, 2]
h = l
l = [3, 4]
print h #-> [1, 2]
The original list in l is still preserved un-modified, and referenced by
the name h. Just binding a different object to an existing name doesn't
change anything about the old object referenced by the name.
More information about the Python-list