Menu
CoddyTech

Bindings and Copy Semantics

Lesson 3 of 48 in Coddy's Python for R Developers course.

R usually presents value-like modification semantics for vectors and lists: after assigning one vector to another name, modifying the second does not alter the first. Implementations can share storage until modification, so this is not a promise of an immediate physical copy. Python assignment shares object references. Rebinding a Python string name leaves aliases unchanged because strings are immutable; mutating a shared Python list changes what every alias sees. R environments are reference objects and are an important exception to ordinary vector behavior. Python uses equals for assignment; the R left-arrow assignment form is not Python assignment syntax.

R

a <- c(1, 2)
b <- a
b[1] <- 9
cat(a, "\n")

Python

label = 'red'
alias_label = label
label = 'blue'
print(alias_label)

Porting trap

Do not infer Python list independence from R vector updates. Copy explicitly when two lists must change independently.

challenge icon

Challenge

Beginner

Read two lines: an initial status and a replacement status. Keep the initial value in original, reassign status to the replacement, then print the original value and current value on separate lines. Both lines can be empty. The input scaffold reads the replacement into replacement.

Print only the requested output, with a newline after each line. The supplied input lines read the test data; keep them and add your work below.

Your code goes in main.py. The locked driver.py starts your program and cannot be edited.

Try it yourself

# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module

run_module("main", run_name="__main__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for R Developers

Practice on your own: Online Python compiler