Programs often store things, and then get them for use later. Say we wanted to put socks into one drawer, and shoes in another drawer.
Then we want to see what is in the drawers. The print() steps will show what is in the drawers. Both drawer1 and drawer2 below are called "variables". It is a fancy name meaning that they can change and hold different things at different times.
The equal sign is not like what you may have seen in math. It will be explained later.
drawer1 = 'socks'
drawer2 = 'shoes'
print(drawer1)
print(drawer2)
socks shoes
The drawer1 can be set to socks, and then set to elephant. Notice that the socks are erased, so the program does not know anything about socks when the steps are completed.
drawer1 = 'socks'
drawer2 = 'shoes'
drawer1 = 'elephant'
print(drawer1)
print(drawer2)
elephant shoes
In programming, someone chose the equal sign to mean something about moving things from one storage place to another. Someone chose a key from the keyboard to mean this. They could have used another key, or even a word.
It might have been more clear to type:
drawer1 <- 'socks'".
In real life, things mostly get moved from one place to another. In programming, the equal sign really means copy.
Things on the right side of the equal sign get copied to the left side, and the left side doesn't change.
drawer1 = 'socks'
drawer2 = 'shoes'
print('before:')
print(drawer1)
print(drawer2)
drawer1 = drawer2
print('after:')
print(drawer1)
print(drawer2)
before: socks shoes after: shoes shoes
The code above shows that the equal sign copied drawer2 to drawer1. The equal sign read from drawer2, and did not change it, so it still contains 'shoes'.
boxA = 'socks'
boxB = 'shoes'
boxA = 'elephant'
print(boxA)
print(boxB)
elephant shoes
The box and drawer variables can also hold numbers.
boxA = 1
boxB = 5
print(boxA)
print(boxB)
1 5
# Tell Python that this is a list by using "[]".
# Initialize the 3 variables with 0
dresser = [0]*3
print(dresser)
dresser[1] = 'socks'
dresser[2] = 'shoes'
print(dresser)
[0, 0, 0] [0, 'socks', 'shoes']
The first print before setting the socks and shoes shows "[0, 0, 0]" Wait a minute. After running this, the second print shows "[0, 'socks', 'shoes']" Why is the first item 0?
Most programming languages like Python count from 0.
dresser = [0]*3
dresser[0] = 'socks'
dresser[1] = 'shoes'
print(dresser)
['socks', 'shoes', 0]
Now the last drawer in the dresser is 0.
Replacing something in the list is the same as replacing in a single variable.
dresser = [0]*3
dresser[0] = 'socks'
dresser[1] = 'shoes'
print('before elephant', dresser)
dresser[1] = 'elephant'
print('after elephant', dresser)
before elephant ['socks', 'shoes', 0] after elephant ['socks', 'elephant', 0]