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
BeginnerRead 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler