mutate dictionary or list

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Tue Sep 7 15:55:47 CEST 2010

Baba a écrit :
> Hi
> 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
> hand).
> 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

Everything in Python is an object. A few objects are immutable (ints, 
strings, tuples...), ie you there's no way to modify the state of the 
object in place. Most objects are mutable, and this obviously includes 
lists and dicts (you can add / remove / replace list or dicts elements).

Now the point is that when passing an object as argument to a function, 
you don't pass a copy of the object but the object itself, so if the 
object is mutable, you can mutate if from within the function.

A simple (and really dumb) example being worth a thousand words:


def update_dict(dic, key, value):
     print "in update_dic : dic id is %s" % id(dic)
     dic[key] = value

def main():
    dic = dict(a=1, b=2)
    lst = [1, 2, 3]

    print "in main : dic id is %s" % id(dic)
    print "dic : %s" % dic
    print "calling update_dict"
    update_dict(dic, "c", 3)
    print "after update_dict"
    print "in main : dic id is %s" % id(dic)
    print "dic : %s" % dic

if __name__ == '__main__':

> I know that a ditionary is unordered. How Can i however avoid
> 'acidental' mutation?

This has nothing to do with dicts being ordered or not. And there's NO 
"accidental" mutation - you have to explicitely call a method or 
operator that mutate the dict.

More information about the Python-list mailing list