Definition
How do you find the unique words in a story?
A tuple is an ordered collection that cannot be changed after it is created, written in round brackets, such as (12.97, 77.59). A set is an unordered collection with no duplicate items, written in curly brackets, such as {"red", "blue"}, and supports operations such as union and intersection.
In simple words
Use a tuple for things that belong together and shouldn't change, such as a point's latitude and longitude or a date. Use a set when you only care whether something is present: putting all the words of a story into a set removes repeats instantly.
Overview
- A tuple is an ordered, immutable collection written with round brackets: (28.6, 77.2).
- A set is an unordered collection of unique items written with braces: {"red", "blue"}.
- Tuples can be dictionary keys and set members because they cannot change; lists cannot.
- Sets remove duplicates automatically and check membership very fast using hashing.
- Tuple unpacking assigns several variables at once: lat, lon = point.
- {} creates an empty dictionary; an empty set must be written set().
Why it matters
Choosing the right collection makes code clearer and faster. Checking whether an item is in a set is far faster than searching a long list, which matters when you handle vocabularies of thousands of words.
Key terms
- Tuple
- An ordered collection that cannot be changed after creation.
- Unpacking
- Assigning the items of a tuple or list to several names at once: x, y = point.
- Set
- An unordered collection of unique items.
- Hashable
- A value that can be stored in a set or used as a dictionary key; immutable values usually are.
- Union and intersection
- Everything in either set, and only what is in both.
- Membership test
- Checking whether a value is present with in.
Types
Python has several fixed-size and unique-item collection types, plus a family of set operations. These are the types to know.
1. Tuple
An ordered, immutable sequence of items.
- How it works: Created with commas (brackets are optional); items are read by index; a one-item tuple needs a trailing comma: (5,).
- Example: rgb = (255, 128, 0); a function returning (minimum, maximum).
- When to use it: Use it for fixed records such as coordinates, dates and RGB colours, and for returning several values.
2. Named tuple
A tuple whose fields also have names, from collections.namedtuple or typing.NamedTuple.
- How it works: It behaves like a tuple but lets you read fields by name, making code self-explanatory, while using little memory.
- Example: City = namedtuple("City", "name lat lon"); delhi.lat instead of delhi[1].
- When to use it: Use it for small, fixed records where field names make code clearer.
3. Set
An unordered, mutable collection with no duplicate items.
- How it works: Items are stored by their hash, so add(), remove() and membership tests take about the same time however big the set is; items must be immutable.
- Example: unique_cities = set(city_list); "Pune" in visited.
- When to use it: Use it to remove duplicates and for fast "have I seen this?" checks.
4. Frozenset
An immutable version of a set.
- How it works: frozenset(items) builds it; it supports all set operations except those that change it, and it can be a dictionary key or a member of another set.
- Example: Storing itemsets such as frozenset({"tea", "sugar"}) as keys when counting shopping baskets.
- When to use it: Use it when a group of items must stay fixed or be used as a key, as in association-rule mining.
5. Set operations
Union (|), intersection (&), difference (-) and symmetric difference (^).
- How it works: Union combines all items; intersection keeps items in both; difference keeps items only in the first; symmetric difference keeps items in exactly one.
- Example: cricket & football gives students who play both; cricket - football gives cricket-only players.
- When to use it: Use them to compare groups, such as customers who bought both products or words shared by two documents.
Explained in detail
Why have a list that cannot change?
A tuple is like a list that has been sealed. It suits data whose parts belong together and should not change independently: a coordinate (latitude, longitude), a date (2024, 8, 15), an RGB colour (255, 165, 0). Sealing protects against accidental changes, lets tuples be used as dictionary keys and set members, and signals intent to other programmers: "this is a fixed record". Functions often return several values as a tuple, which you unpack straight into names: lowest, highest = min_max(marks).
Tuple details
- The comma makes the tuple, not the brackets: t = 5, is a one-item tuple, while (5) is just the number 5.
- Tuples support indexing, slicing, len(), in and loops, like lists.
- Unpacking works with any sequence; first, *rest = [1, 2, 3] puts 1 in first and [2, 3] in rest.
- A tuple holding a list can still have that list changed; immutability is only one level deep.
Sets: uniqueness and speed
A set keeps only one copy of each value, so set(["red", "blue", "red"]) is {"red", "blue"}. The quickest way to remove duplicates from a list is list(set(items)), though this loses the original order. Sets are built on a structure called a hash table, which lets Python check x in s almost instantly however large the set is, while checking x in a list means looking at items one by one. For a list of a million names, that difference is dramatic. Note that {} creates an empty dictionary; an empty set is set().
Set operations
| Operation | Symbol | Example: a = {1, 2, 3}, b = {2, 3, 4} |
|---|---|---|
| Union | a | b | {1, 2, 3, 4} |
| Intersection | a & b | {2, 3} |
| Difference | a - b | {1} |
| Symmetric difference | a ^ b | {1, 4} |
| Subset test | a <= b | False |
These operations answer real questions quickly: which students took both Maths and Science (intersection), which words appear in one document but not another (difference), how many distinct visitors came on either day (union). In NLP, the vocabulary of a text, the set of distinct words it uses, is literally a Python set.
How it works
| list | tuple | set | |
|---|---|---|---|
| Brackets | [ ] | ( ) | { } |
| Ordered | Yes | Yes | No |
| Changeable | Yes | No | Add and remove only |
| Duplicates | Allowed | Allowed | Removed |
Sets support maths-like operations: a | b (union, everything in either), a & b (intersection, only what is in both) and a - b (difference).
In code
A tuple for a fixed location, and sets for unique and shared words. Sets have no order, so they are sorted before printing.
location = (18.52, 73.86) # latitude, longitude of Pune
lat, lon = location
print("Latitude:", lat, "Longitude:", lon)
story = "the cat sat on the mat and the cat slept"
words = story.split()
unique = set(words)
print("Words:", len(words), "Unique:", len(unique))
print("Unique words:", sorted(unique))
mine = {"python", "maths", "art"}
yours = {"python", "music", "maths"}
print("Both like:", sorted(mine & yours))
print("Either likes:", sorted(mine | yours))
print("Is 'art' in mine?", "art" in mine)Output
Latitude: 18.52 Longitude: 73.86 Words: 10 Unique: 7 Unique words: ['and', 'cat', 'mat', 'on', 'sat', 'slept', 'the'] Both like: ['maths', 'python'] Either likes: ['art', 'maths', 'music', 'python'] Is 'art' in mine? True
Try it yourself
List, tuple or set?
Which collection fits each job best?
Every different word used in a book
Today's to-do items, which you'll add to and tick off
The (red, green, blue) values of one fixed colour
Usernames already taken, checked often
Marks in the order students sat the test
Common mistakes
- Writing (5) for a one-item tuple. It needs a comma: (5,).
- Expecting a set to keep order or allow duplicates.
- Using {} for an empty set. That's an empty dictionary; use set().
Check yourself
Summary
- Tuples are ordered and fixed; use them for values that belong together.
- Sets are unordered with no duplicates; great for unique items and fast checks.
- Union |, intersection & and difference - work on sets.
Finished reading?
Sources: Python docs: Data Structures