-1

I'm using Python 3.4.2 with PyDev, grammar 3.0. Can you explain the illustrated behaviour?

    # Program to demonstrate behaviour"not understood" regarding list                <insert()>
    forLoopCt=0                             # init for loop counter
    brkSw=0                                 # init a break switch to prevent infinite loop
    words=['cat', 'window', 'defenestrate','extra','another long one']
    wordscpy=words                          # We want to use this copy to loop thru
    print(wordscpy)                         # just show initial list

    for w in wordscpy:
        print('brkSw='+str(brkSw),end=' ')  # will print 0 until we have used insert

        if brkSw>1:                         # to control stopping of the loop
            print('','...Breaking at top of loop...')
            break

        print('w='+w,\
              'len='+str(len(w)),end=',')   # show current loop element

        if len(w)>6:
            print('long,')
            words.insert(1, w)              # when we do this...
            '''... the <for w in wordscpy> loop continues - re-accessing the last w
            (the one just inserted?) - don't understand why both <words> and <wordscpy>
            are maintained the same
            - same behaviour for any valid value of insert index (0 ...-1)
            - for loop never gets to complete - never accesses 'extra' '''
            print('inserted',w)
            print('wordscpy =',wordscpy)    # shows that <wordscpy> also changes (?!!)
            print('words =',words)          # in sync with the change to <words>

            brkSw+=1                        # to insure we will break (else infinite loop!)

        forLoopCt+=1                        # incr loop count                         
        print('loop count='+str(forLoopCt)) # and show it

    print('program ends')

Why are wordscpy and words identical twins when we only tried to modify words?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
  • 1
    `wordscpy=words` **does not** create a copy, it just means both names reference the same object. See e.g. http://nedbatchelder.com/text/names.html (and change to ` wordscpy=words[:]`). – jonrsharpe Feb 16 '15 at 22:51
  • I now understand. ObjectB=ObjectA assigns ObjectB as an alias for ObjectA. If ObjectB is meant to be a COPY, we have to make it a copy, e,g, ObjectB=list(ObjectA) for list objects, or ObjectB=ObjectA[:], et al. Thanks so much. – user306651 Feb 17 '15 at 19:01

1 Answers1

2

wordscpy and words are identical because they share the same reference. In order to change this intended functionality, try:

import copy

wordscpy = copy.copy(words) # make a copy, don't share reference
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70