Menu
CoddyTech

unique and Shallow Copies

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

R unique removes duplicate values while retaining a vector result. Python set represents unique hashable elements but has no promised iteration order. Sort it for deterministic output. R ordinary list modifications behave value-like, while Python shallow copies share referenced nested objects. An environment stored inside an R list remains a reference object, so R also has forms of nested sharing. Python list.copy only creates a new outer list. An alias created by plain assignment shares even the outer list. Decide which levels must be independent before copying. Use set() for an empty Python set because empty braces create a dict.

R

a <- list(c(1))
b <- a
b[[1]] <- c(b[[1]], 2)
cat(a[[1]], "\n", sep="")
cat(sort(unique(c(3, 1, 3))), "\n")

Python

a = [[1]]
b = a.copy()
b[0].append(2)
print(a)
print(sorted({3, 1, 3}))

Porting trap

Do not assume an R list modification example predicts Python nested-list behavior. Track which objects are copied and which are referenced.

challenge icon

Challenge

Beginner

Read three integers on separate lines: an initial value, a replacement, and an extra value, each from -20 to 20. The scaffold creates a nested list, an alias of it, and a shallow copy. Through the alias, replace the nested integer with the replacement. Append [extra] to the shallow copy only. Print the original nested list, the shallow copy, and a sorted list of the distinct three input integers, each on its own line. Use Python list format.

Print only the requested output, with a newline after each line. Keep the supplied input scaffold. No loops or functions are needed.

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