Menu
CoddyTech

dup, Copies, and Sets

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

Ruby dup and Python list copy make a new outer container with shared element objects. Assignment shares the outer object too. If you mutate a nested list through a shallow copy, the original sees the change. Replacing an outer slot is different because the outer containers are independent. Ruby requires the standard-library set implementation for Set; Python has a built-in set. Both remove duplicate elements, but do not use set iteration order as a portable output contract. Sort comparable elements before printing. Python {} is an empty dictionary, so construct an empty set with set().

Ruby

a = [[1]]
b = a.dup
b[0] << 2
p a

Python

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

Porting trap

A shallow copy is not a backup of nested mutable state. Copy each needed level or use copy.deepcopy when recursive independence is required.

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 Ruby Developers

Practice on your own: Online Python compiler