Copies, aliases and safe loops

Lists & Tuples, lesson 4 of 6

📋 Lists & Tuples, lesson 4 of 6

Copies, aliases and safe loops

Understand why changing one list can change 'another', and how to copy.

10 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

A variable doesn't contain a list; it points to one. So b = a does not copy anything. It gives the same list a second name (an alias). Change it through either name and both "see" the change.

Example

Two names, one list

is checks whether two names point to the very same object.

To get an independent copy, use any of these:

  • items.copy()
  • list(items)
  • items[:] (a slice of everything)

== compares contents; is compares identity (same object).

Example

A real copy

Replace .copy() with [:]. Same result!

Walkthrough

Alias or copy?

originallist102132
Step 1 of 4

original = [1, 2, 3] creates a list and points the name original at it.

shared list
separate copy
Quiz

What does this print?

Example

The skipping bug

The goal was only odd numbers, but one 2 and one 4 slipped through.

Walkthrough

Why items get skipped

12234450123456index 0
Step 1 of 7

Behind the scenes, the loop walks an index: 0, 1, 2, ... At index 0, n is 1: odd, so it stays.

n (this pass)
removed
skipped, never checked
Example

The fix: build a new list

Another fix: loop over a copy with for n in nums[:]: and remove from nums.

Quiz

What does this print?

Exercise

Filter the inbox

Build a new list clean with every message from inbox except "SPAM", in the same order. Leave inbox unchanged.