Click here to Skip to main content
15,885,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
word = "pop"
for char in "corn":
    word += char
print(word)


What I have tried:

i tried to changing the strings
Posted
Updated 20-Sep-21 20:18pm

This works because variables are not immutable and the fragment word += char is equivalent to word = word + char, so rather than appending a character to the end of the variable, this creates a new string consisting of the value of the current value of word with thee new character appended to it, then assigns that value to the variable word
 
Share this answer
 
Python strings are immutable, which just means that once created they can't be changed, just like numbers.
If you have 6 apples and I have 6 oranges, then you eat an apple that doesn't mena I have 5 oranges left! :laugh:

Think about it:
Python
x = 666
x = x + 1
y = 666
print(x)
print(y)
You expect that to print 667 and 666 - because if it didn't, code would be a real problem!
How about this:
x = 666
y = x
x = x + 1
print(x)
print(y)
Again, you expect 667 and 666 because y holds a copy of the value in x not the "same value as x"

Strings do the same thing:
Python
x = '666'
y = x
x = x + '1'
print(x)
print(y)
Prints "6661" and "666" because the string is as immutable as a number: once created a string can't be changed, so any attempt creates a new string and returns that instead.

Make sense?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900