Skip to the workspace
Pebellslearn by building
Fundamentals  ›  Lesson

Lists, Tuples & Sets

Lists, Tuples, Sets 22 minA list is an ordered, mutable collection. A tuple has fixed slots. A set holds distinct elements without positional indexing.

A list is an ordered, mutable collection. A tuple has fixed slots. A set holds distinct elements without positional indexing.

Choose a collection for the job and distinguish changing a container from changing an object stored inside it.

A grocery order needs sequence and repeats; a booking record needs fixed positions; a paid-members collection needs uniqueness. Choose the container from that information, then inspect what happens when two names share it. Fixed outer slots and deeply unchangeable contents are different promises.

Three cards side by side: a list in square brackets holding atta, dal, atta at positions 0, 1, 2, which grows with append and is ticked for order, change and repeats; a padlocked tuple holding a train number, a city and a seat, where assigning to b[2] is a TypeError; a set drawn as a loose bag of names with no positions, where adding Ravi again is ignored

Plan a grocery list

A shopping list grows, shrinks and gets reordered: a list is the right fit. Positions work exactly like string positions, from 0, with -1 for the last item:

python

Your flatmate sends two more items as a list. append looks right, but:

What does this print?
cart = ["atta", "dal"]
cart.append(["milk", "eggs"])
print(len(cart))

Methods such as append, extend and sort change a list in place and return None; pop instead returns the removed item. That distinction makes this one of the most common bugs in Python:

broken — fix it

Run it: the cart is gone. Keep the cart and sort it.

sorted(x) makes a new sorted list and leaves x alone; x.sort() sorts x itself and gives back nothing.

Preparing this topic’s interactive investigation…

Store a train booking

A booking is a fixed record: train number, from, to, seat. The parts belong together and should not drift, so use a tuple. Unpacking gives each part its own name in one line, and a * name scoops up "everything in between":

python

The seat changes. A tuple refuses to be edited, which is the whole point:

broken — fix itTypeError

Run it and read the error. Then make a new booking with seat B4-33.

That ("B4-33",) needs its comma. Round brackets on their own only group:

What does this print?
coach = ("AC")
print(type(coach).__name__)

A tuple can be a set item or dict key only if all its elements are hashable. A tuple containing a list fails that requirement. The fixed slots alone do not establish hashability.

A tuple fixes its slots, not every object inside

python

record[1] = [] would try to replace a tuple slot and raise TypeError. Calling append follows the existing reference to a mutable list instead. Hashable means an object supplies a stable hash compatible with equality; sets and dict keys use that contract for lookup. Strings and integers qualify; lists do not. Tuples qualify when every element qualifies.

A set keeps one representative of equal values and does not promise a useful iteration order. It therefore answers “which items exist?” while a list can answer “which arrived first, and how many times?” Removing duplicates loses information; keep counts separately when repeated occurrences matter.

Check who paid

Four friends split a cab. The payments list says who has paid, but Ravi's UPI transfer came through twice. A set drops the duplicate, and set operators answer the real question, who still owes?

python

A set has no positions, so paid[0] is a TypeError, and printing a set may show the items in any order. That is why we print sorted(...).

Removing someone who might not be there is the usual crash:

broken — fix itKeyError

Run it and meet KeyError. Make it print the two names without crashing.

Use .remove() when a missing item means something already went wrong, and .discard() when "maybe not there" is normal.

The one-liner: list comprehensions

"Start an empty list, loop, append" is so common it has a short form, the list comprehension: [expression for item in things if condition].

python

Use it for one simple step per item. When the logic needs several lines, the plain loop reads better. (Python also has array and NumPy arrays for long runs of numbers; for everyday work a list is the default.)

Traps worth knowing

b = a does not copy a list. It sticks a second name tag on the same list, so a change through either name shows up in both:

Two name tags, asha and ravi, both tied to one list box; ravi.append adds chips and asha sees it too. Below, ravi = asha.copy() gives ravi his own box, so cola only goes into his

What does this print?
asha = ["atta", "dal"]
ravi = asha
ravi.append("chips")
print(len(asha))

Step through both versions, the shared tag and the real copy:

step through it
1asha = ["atta", "dal"]
2ravi = asha
3ravi.append("chips")
4own = asha.copy()
5own.append("cola")
6print(asha, own)

A copy separates one layer

python

Draw two outer boxes with arrows to the same first row. copy() duplicates the outer sequence of references, not each referenced object. Copying each row separates this two-level structure; arbitrary nesting needs a deliberate ownership policy, sometimes copy.deepcopy.

For independent practice, create three empty rows for a grid. Compare [[]] * 3 with [[] for _ in range(3)] by changing only row zero. Explain why one expression repeats references while the other constructs three lists. Check identity with is, not just equality of their initial values.

Changing a list while you loop over it skips items, because the loop moves on by position while the items shuffle left:

What does this print?
nums = [5, 0, 0, 7]
for n in nums:
    if n == 0:
        nums.remove(n)
print(nums)

Quick practice

What does this print?
print(type({}).__name__)
What does this print?
x = [1, 2, 3]
y = x[:]
y.append(4)
print(len(x))
broken — fix itTypeError

Print the name that comes first alphabetically.


🎯 Your turn

Write unique_dishes(orders). It takes a list of dish names (with duplicates) and returns a sorted list of the unique names:

  • unique_dishes(["soup", "steak", "soup", "salad"]) → ["salad", "soup", "steak"]
  • unique_dishes([]) → []

Hint: set(orders) drops the duplicates, and sorted(...) gives back an ordered list. Together: sorted(set(orders)).

Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from reversing a list to a small number analyser.

Your task
Build unique_dishes(orders). It takes a list of ordered dish names (with duplicates) and returns a sorted list of the unique names. Example: unique_dishes(["soup", "steak", "soup"]) → ["soup", "steak"] sorted → ["soup", "steak"].

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upReverse a list

Write reverse(items) returning a new reversed list, using slice syntax (not .reverse()).

slicing
DrillHead and tail

Write head_tail(items) returning [first, rest_list] — the first item and a list of the rest. Empty list → [None, []]. Use star-unpacking.

star-unpackingguard
BuildDedupe, keep order

Write dedupe(items) returning the items with duplicates removed but original order preserved. Use a seen set.

setloop
BossList diff

Write diff(old, new) returning {"added": [...], "removed": [...], "common": [...]} — items only in new, only in old, and in both. Each list sorted ascending.

set-opssorteddict
CapstoneAnalyze numbers

Write analyze(nums) returning {"unique": [...], "duplicates": [...], "top": <max>} — sorted unique values, sorted values that appear more than once, and the largest. Empty → {"unique": [], "duplicates": [], "top": None}.

setcomprehensionmaxdict
Project context and further resources
You're building a piece ofBill Splitter & Tip Calculator
This piece — unique_dishes(): The distinct dishes the table ordered (de-duplicated).
Scenario The table shouts orders and some dishes are repeated. The app needs a clean, alphabetised list of the distinct dishes ordered.
unique_dishes.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
unique_dishes(orders) → listThe de-duplicated, sorted list of dishes the table ordered.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.