Computer Science Researcher • Educator • Programming Instructor
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.
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.
fruits = ("apple", "banana", "mango")
print(fruits[0])
print(fruits[1])
Output:
apple
banana
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.
A set is an unordered collection of unique items. Sets do not allow duplicates, and they do not keep items in any specific order.
my_set = {"apple", "banana", "apple", "mango"}
print(my_set)
Output (order may vary):
{'banana', 'apple', 'mango'}
Notice that the duplicate "apple" was removed automatically.
numbers = {1, 2, 3}
numbers.add(4)
print(numbers)
Output (order may vary):
{1, 2, 3, 4}
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.
1. What is a key feature of a tuple?
It can change freely2. Which symbol is used to create a tuple?
[]3. What is a key feature of a set?
Keeps items in order4. What will this output?
t = (4, 8, 12)
print(t[1])
45. What happens when you add a duplicate to a set?
It shows twice