LEARN PYTHON | Tuples And Sets

Lesson objective

Use tuples for fixed ordered groupings and sets for unique membership, and explain ordering, mutability, unpacking and hashable-item requirements.

Learn

03.3 | TUPLES AND SETS

01 | COLLECTIONS HAVE DIFFERENT PROMISES

A list is useful when order and change matter. A tuple suits a fixed ordered grouping such as a coordinate pair. A set suits unique membership, such as the distinct activities selected by a club.

Do not choose from bracket shape alone. Ask whether duplicates matter, whether positions carry meaning and whether the collection itself must change.

Each structure can hold references to objects. Its rules determine what operations are valid, and those rules are part of the data design.

02 | TUPLES KEEP AN ORDERED GROUP

A tuple stores values in order and supports indexing, negative indexing and slicing. A pair (4, 7) can represent x and y coordinates, where position has an agreed meaning.

The tuple itself is immutable: you cannot replace its item at index zero or append another item. You can bind the variable to a new tuple, just as a name can be rebound to a new string.

position = (4, 7)
print(position[0])
print(position[-1])

EXPECTED OUTPUT

4
7

03 | THE COMMA MAKES A ONE-ITEM TUPLE

For one item, write (4,), including the comma. (4) is just an integer expression grouped in parentheses. The empty tuple is ().

Commas create tuple packing; parentheses make its boundary readable. result = 4, 7 also creates a tuple. Prefer clear grouping when a tuple is passed to another operation.

single = (4,)
not_a_tuple = (4)
print(type(single))
print(type(not_a_tuple))

EXPECTED OUTPUT

<class 'tuple'>
<class 'int'>

04 | UNPACK MEANINGFUL POSITIONS

Unpacking assigns successive items to successive names. x, y = position makes x four and y seven. The number of destination names must match the number of supplied items for this basic form, or ValueError is raised.

Good names document what the positions mean. A two-item tuple can be practical; a long tuple whose meanings are hard to remember may be better expressed with a dictionary of named fields.

position = (4, 7)
x, y = position
print("x:", x, "y:", y)

EXPECTED OUTPUT

x: 4 y: 7

05 | IMMUTABLE DOES NOT MEAN EVERYTHING INSIDE IS FROZEN

A tuple’s references cannot be replaced in place, but it can contain a mutable object such as a list. That inner list can still change.

For record = ("Maya", [8, 9]), appending to record[1] changes the list stored there, not the tuple’s slot. Assigning record[1] = another_list would instead try to replace a tuple item and fail.

Explain the level at which immutability applies rather than calling the entire nested structure permanently frozen.

record = ("Maya", [8, 9])
record[1].append(10)
print(record)

EXPECTED OUTPUT

('Maya', [8, 9, 10])

06 | A SET STORES DISTINCT MEMBERS

A set contains unique items and supports membership tests with in. Repeated equal items collapse into one member. A set does not provide a positional index or promise a display order.

Use set() for an empty set. {} creates an empty dictionary, which is introduced next. A non-empty set literal uses braces, such as {"robotics", "coding"}.

Converting a list to a set removes duplicates but loses its positional sequence information. A set is not a sorted list.

activities = {"coding", "robotics", "coding"}
print(len(activities))
print("coding" in activities)

EXPECTED OUTPUT

2
True

07 | ADD, DISCARD AND REMOVE

add(value) inserts a set member; adding an existing member leaves membership unchanged. discard(value) removes it if present and does not raise an error if absent.

remove(value) also removes a member, but raises KeyError when it is absent. Choose according to whether absence is expected or should expose a fault.

These methods mutate the set and return None. Do not assign the method result back as though it were the changed collection.

activities = set()
activities.add("coding")
activities.add("coding")
activities.discard("music")
print(len(activities))

EXPECTED OUTPUT

1

08 | COMPARE MEMBERSHIP BETWEEN GROUPS

Union gives members appearing in either set. Intersection gives shared members. Difference gives members in the first set but not the second.

Use | for union, & for intersection and - for difference. Difference is directional: A - B is not generally the same as B - A. These expressions create resulting sets rather than altering their operands.

When you need predictable readable display for simple comparable strings, sorted(result) produces a sorted list. That is a display choice, not a change to the set’s ordering rule.

first = {"coding", "robotics"}
second = {"robotics", "music"}
print(sorted(first | second))
print(sorted(first & second))
print(sorted(first - second))

EXPECTED OUTPUT

['coding', 'music', 'robotics']
['robotics']
['coding']

09 | MEMBERS MUST BE HASHABLE

A set uses hashing to organise membership. A hashable object has a stable hash and equality behaviour suitable for that role. Strings and integers are suitable common examples; lists and dictionaries are not.

A tuple is hashable only if all its items are hashable. A coordinate tuple of numbers can be a set member, but a tuple containing a list cannot.

The beginner rule “all immutable things work” is too broad without checking their contents. Start with simple text, numbers and suitable tuples.

10 | EXPLORE UNIQUE MEMBERS AND SHARED ACTIVITIES

Enter comma-separated simple activity names for two groups. The demo trims surrounding spaces, ignores empty pieces and treats names as case-sensitive. It shows sorted display lists so the output is predictable.

Try repeated values, no shared values and an empty group. Explain why this tool does not assign numbered positions to set members.

11 | YOUR COLLECTION-CHOICE CHALLENGE

Store a coordinate pair in a tuple and unpack its two meanings. Separately, collect club activity names and use sets to report shared and distinct choices.

Test duplicate activity names and an absent member removal. Explain why discard is suitable if the removal request is optional, while remove can reveal an unexpected absence.

Extension: compare a tuple containing a list with a tuple containing only numbers. Explain which can be a set member and why.

PUT YOUR SKILLS TO WORK

Use the Section 3 challenges to practise these ideas independently. Work in your Python editor, predict results and keep a short test record.

Section 3 challenges Python course navigation

MATCH THE PYTHON TERM TO ITS MEANING

Terminology

Terminology

Tuple

An ordered immutable collection of references.

Packing

Combining values into a tuple.

Unpacking

Assigning successive items to names.

One-item tuple

A tuple written with a necessary comma, such as (4,).

Tuple immutability

Its item references cannot be replaced in place.

Nested mutable item

An inner object that can change even inside a tuple.

Set

A collection of distinct hashable members without positional ordering.

set()

Creates an empty set with no argument.

Unique member

One equal value is represented only once.

Membership

Testing whether an item is present.

add()

Adds a set member.

discard()

Removes a member if present.

remove()

Removes a member or raises KeyError if absent.

Union

Members in either set.

Intersection

Members shared by both sets.

Difference

Members in the first set but not the second.

Hashable

Suitable stable hash/equality behaviour for keys and set membership.

Predictable display

Sorting suitable members for output without making the set positional.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which describe tuples?
2. Which are tuples?
3. Which describe unpacking?
4. Which describe a tuple containing a list?
5. Which describe sets?
6. Which describe empty collections?
7. Which operations find shared or combined members?
8. Which can be set members here?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Compare a tuple with a list.

2. Explain (4,) versus (4).

3. Explain unpacking a coordinate pair.

4. Explain a mutable list inside a tuple.

5. Compare sets with lists.

6. Explain discard versus remove.

7. Calculate union and intersection for {a,b} and {b,c}.

8. Explain a tuple’s hashability.

CODE IT | YOUR INDEPENDENT CHALLENGE

Store a fixed coordinate and compare two sets of club members. Explain which collection fits each purpose.

Work in your Python editor. Keep a working version, explain one design choice and record at least two tests. Use the Learn tab for worked examples before comparing your result.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

    Selections are kept while this page is open.

    Workbook

    Workbook

    COMING SOON

    The workbook for Tuples And Sets is coming soon. Complete the matching task and written questions in your exercise book.