Re: mutate dictionary or list

Discussion in 'Python' started by Bruno Desthuilliers, Sep 7, 2010.

  1. 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:

    # mutate.py

    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__':
    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.
    Bruno Desthuilliers, Sep 7, 2010
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Carlo v. Dango

    how to mutate a tuple?

    Carlo v. Dango, Oct 14, 2003, in forum: Python
    Replies:
    10
    Views:
    854
    John Roth
    Oct 14, 2003
  2. mike p.
    Replies:
    1
    Views:
    308
    Terry Reedy
    Feb 27, 2004
  3. toton
    Replies:
    23
    Views:
    916
    Chris Uppal
    Nov 2, 2006
  4. Rick Johnson
    Replies:
    51
    Views:
    562
    Rick Johnson
    Feb 12, 2013
  5. Jean-Michel Pichavant
    Replies:
    0
    Views:
    91
    Jean-Michel Pichavant
    Feb 11, 2013
Loading...

Share This Page