Brainlag
  1. Library
  2. Concepts
  3. Python

Names and values

A Python variable is a name that points at a value. Two names can point at the same value, and that matters once the value can change.

Python8 min

A name points at a value

= does not copy anything into a box. It takes the value on the right and points the name on the left at it. Step through this and watch the arrows.

Step through it
hp = 100
damage = 30
hp = hp - damage
backup = hp
hp = 0

When backup = hp runs, backup points at the same value as hp (70). Moving hp to 0 afterwards does not drag backup with it. Each name moves on its own.

Two names, one list

Numbers and strings never change, so sharing them is harmless. A list can change. If two names point at the same list, a change made through one name shows up through the other.

Step through it
squad = ["Ana", "Ben"]
team = squad
team.append("Cleo")
print(squad)

team = squad made a second arrow to the same list, not a copy. Want a separate list? Ask for one: team = squad.copy().

Run it: a copy and a shared list

Run it, then change one thing and run it again.

main.py to run
squad = ["Ana", "Ben"]
shared = squad          # a second name for the same list
copied = squad.copy()   # a new list with the same items

squad.append("Cleo")
print("shared:", shared)
print("copied:", copied)

Keep the original playlist

shuffled should be a separate list, so adding a song to it leaves playlist alone. Right now both lists change. Fix the second line.

exercise_1.py to run
playlist = ["Intro", "Neon Rain"]
shuffled = playlist
shuffled.append("Bonus Track")
print(playlist)
print(shuffled)

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.