Ending up: how does defining new_word work?



My code works correctly but I want to know why defining new_word twice, works.

First I define new word which is: new_word = word + first + pyg then in the next line I slice the first letter off of new_word, which then creates word + first + pyg correctly. What makes it keep the sliced part rather than the first definition of new_word?

pyg = 'ay'

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
    print original
    word = original.lower()
    first = word[0]
    new_word = word + first + pyg
    new_word = new_word[1:len(new_word)]
    print new_word
    print 'empty'


You use = which overwrites the memory address new_word was looking at. However until it has finished running you can call what new_word is/used to be looking at.


Sorry, I'm not sure that I get it. By using '=' I overwrite what new_word is - ok that's fine, but why doesn't it just print the slice section of: new_word[1:len(new_word)]. It still goes back and adds it to the first + pyg.



It still goes back and adds it to the first + pyg.

It doesn't when you create new_word is doesn't just reference the other variables, it creates a new string in memory containing everything and new_word points to it. When you then slice it, you use that newly created string and create another string that only contains the slice and new_word then points to that.

>>> new_word = word + first + pyg 
>>> print new_word

>>> print word

>>> word = "done" # change the variable word's value from "test" to "done"

>>> print new_word # print new_word but it hasn't changed, even though we changed word.

>>> print new_word[1:len(new_word)]

>>> new_word = new_word[1:len(new_word)]
>>> print new_word

Hopefully that will make it more clear. This is wil original ="test".


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.