Opening Scenario

You wrote a helper to clear a shopping cart before re-populating it:

# Python
def reset_cart(cart):
    cart = []

items = [1, 2, 3]
reset_cart(items)
print(items)   # [1, 2, 3] — nothing happened?!

You tweak it to actually mutate:

def reset_cart(cart):
    cart.clear()

items = [1, 2, 3]
reset_cart(items)
print(items)   # [] — now it works

Same argument. Same function signature. Different behavior. A Java colleague walks past and says "Java passes by value, that's why." A C++ colleague overhears and says "actually C++ has both." Now you're confused about a language you thought you knew.

What's really going on?


Question Progression

Q1: When you "pass an argument to a function," what is actually copied?

Question: In the snippet above, you passed items to reset_cart. Inside the function, the parameter is also called cart. Are items and cart the same thing? If you reassign cart, why doesn't items change?

Reasoning:…

In the full tutorial

  • When to Reach for This

Glossary history

Click dotted jargon to save explanations here.