Tuples and Sets in Python
As you learn Python, you will encounter different ways to store and organize data. Two common types are tuples and sets.
They may look similar at first, but they behave very differently and are used in different situations.
Tuples
Tuples are ordered collections of items that cannot be changed after creation.
Creating a Tuple
my_tuple = (1, 2, 3)
Tuples are useful when the data should stay constant, such as GPS coordinates or a student's birthdate.
Characteristics of Tuples
- Tuples are ordered, so the position of each item matters.
- They cannot be changed (immutable).
- You can still access items by index, for example
my_tuple[0]
.
Sets
Sets are unordered collections of unique elements.
Creating a Set
my_set = {1, 2, 3}
Sets are useful when you need to store unique values, such as a list of unique IDs or a collection of unique items.
Characteristics of Sets
- Sets remove repeated values automatically.
- You can add or remove items at any time.
- The order is not guaranteed because sets are unordered.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.