π Tuples & Sets in Python#
Welcome to the world of Tuples and Sets! These are special types of collections in Python that have unique features and uses. Letβs explore what makes them different and how you can use them effectively. π
1. Tuples (Immutable Lists) π#
What is a Tuple?#
A tuple is an ordered collection of items, just like a list, but cannot be changed (immutable) after creation.
How to Create a Tuple#
Use parentheses ( )
or just commas:
my_tuple = (1, 2, 3)
another_tuple = "a", "b", "c"
Accessing Tuple Items#
Access by index just like lists:
print(my_tuple[^0]) # 1
print(my_tuple[-1]) # 3
Why Use Tuples?#
- They are immutable β safer for data that shouldnβt change.
- Tuples can be used as keys in dictionaries.
- Slightly faster than lists.
Tuple Operations#
- You cannot add, remove, or change items once a tuple is created.
- You can concatenate and repeat tuples like lists:
t1 = (1, 2)
t2 = (3, 4)
print(t1 + t2) # (1, 2, 3, 4)
print(t1 * 2) # (1, 2, 1, 2)
2. Sets (Unordered Unique Collections) π§©#
What is a Set?#
A set is an unordered collection of unique items.
Creating a Set#
Use curly braces { }
or the set()
function:
my_set = {1, 2, 3}
another_set = set([1, 2, 2, 3]) # duplicate 2 will be removed
Key Features#
- Sets do not allow duplicates.
- Elements are unordered (no indexing or slicing).
- Sets are mutable β you can add or remove elements.
Basic Set Operations#
Operation | Description | Example | Result |
---|---|---|---|
add(item) | Add an item | my_set.add(4) | Adds 4 |
remove(item) | Remove an item | my_set.remove(2) | Removes 2 |
union() | Combines two sets | `{1, 2} | {3, 4}` |
intersection() | Common elements | {1, 2} & {2, 3} | {2} |
difference() | Items in first not second | {1, 2, 3} - {2, 3} | {1} |
Practice Questions with Solutions π #
- Practice: Create a tuple of three animals and print the second animal.
- Solution:
animals = ("cat", "dog", "fish")
print(animals[^1]) # dog
- Practice: Try adding “cat” to a tuple. What happens?
- Solution: Tuples are immutable; you cannot add elements.
- Practice: Create a set from `` and print it.1
- Solution:
numbers = set([1, 2, 2, 3])
print(numbers) # {1, 2, 3}
- Practice: Find the union of
{1, 2}
and{2, 3}
.- Solution:
set1 = {1, 2}
set2 = {2, 3}
print(set1.union(set2)) # {1, 2, 3}
Step-by-Step Mini Project: Unique Guest List π#
Task: Create a guest list where duplicates are removed automatically.
guest_list = ["Alice", "Bob", "Alice", "Eve"]
unique_guests = set(guest_list)
print("Unique guests:", unique_guests)
Output:
Unique guests: {'Alice', 'Bob', 'Eve'}
Checklist for This Chapter β #
- Created and accessed tuples
- Understood immutability of tuples
- Created and modified sets
- Used basic set operations like union and intersection
Youβve unlocked two powerful data-collection types in Python! Use tuples when data shouldnβt change, and sets when you need unique items without order. Keep experimenting! π―
β