Lesson 12 – Tuples & Sets

In Python, tuples and sets are two special types of collections. They store multiple items just like lists, but each behaves differently and is used in different situations.

What Is a Tuple?

A tuple is a collection of items that cannot be changed once created. This property is called immutability. Tuples are useful when you want your data to stay safe and unmodified.

Example 1: How do we create and access a tuple?

fruits = ("apple", "banana", "mango")

print(fruits[0])
print(fruits[1])
    

Output:

apple
banana
    

Example 2: What happens if we try to change a tuple?

numbers = (2, 4, 6)
# numbers[0] = 10   # This will cause an error
print(numbers)
    

Output:

(2, 4, 6)
    

Python does not allow changing tuple values. This ensures the data remains protected.


What Is a Set?

A set is an unordered collection of unique items. Sets do not allow duplicates, and they do not keep items in any specific order.

Example 3: How do we create a set?

my_set = {"apple", "banana", "apple", "mango"}
print(my_set)
    

Output (order may vary):

{'banana', 'apple', 'mango'}
    

Notice that the duplicate "apple" was removed automatically.

Example 4: How do we add an item to a set?

numbers = {1, 2, 3}
numbers.add(4)
print(numbers)
    

Output (order may vary):

{1, 2, 3, 4}
    

Example 5: How do sets handle order?

colors = {"red", "blue", "green"}
print(colors)
    

Output:

{'green', 'blue', 'red'}
    

Each time you print a set, the order may appear differently. This is normal and expected because sets are unordered.


Quiz: Test Your Understanding

1. What is a key feature of a tuple?

It can change freely
It is unordered
It cannot be changed
It removes duplicates
Correct answer: It cannot be changed

2. Which symbol is used to create a tuple?

[]
{}
()
<>
Correct answer: ()

3. What is a key feature of a set?

Keeps items in order
Allows duplicates
Stores unique items only
Works like a list
Correct answer: Stores unique items only

4. What will this output?

t = (4, 8, 12)
print(t[1])
        
4
8
12
Error
Correct answer: 8

5. What happens when you add a duplicate to a set?

It shows twice
It causes an error
It is ignored
It changes to a list
Correct answer: It is ignored
Back to Top