In this lesson of the Python mini course, I want to cover two collection types that are used frequently in day-to-day development: tuples and sets in Python. Although they may look similar to lists at first glance, each has specific characteristics that make it ideal for different situations.
A tuple is an ordered, immutable collection of elements. Like lists, tuples can contain any type of data: integers, strings, objects, other collections… But unlike lists, they cannot be changed after they are created. This means you cannot add, remove, or change elements of a tuple once it has been defined.
The syntax is simple:
coordinates = (10.5, 20.3)
Accessing elements works the same way as with lists:
print(coordinates[0]) # output: 10.5
Tuples are useful when we want to guarantee that the data will not be modified. They are also faster to read and use less memory. A typical case where I use a tuple is to represent fixed pairs of values, such as geographic coordinates, RGB colors, or multiple return values from functions:
def divide(numerator, denominator):
if denominator == 0:
return (None, "Division by zero")
return (numerator / denominator, None)
Because they are immutable, tuples are also safe to use as dictionary keys:
points = {}
points[(1, 2)] = "A"
points[(3, 4)] = "B"
This is useful in scenarios such as caching or coordinate mapping, where I need to access data based on fixed pairs.
Sets in Python, on the other hand, are unordered collections with no duplicate elements. The set structure is very similar to sets in mathematics. And that saves me when I want to automatically remove duplicates from a list:
names = ["Ana", "Carlos", "Ana", "João"]
unique_names = set(names)
print(unique_names) # output: {'Carlos', 'João', 'Ana'}
It is important to remember that the order of the elements is not guaranteed. If you need to preserve order, sets may not be the best choice.
Another thing I really like about sets is set operations. Python offers direct support for union, intersection, and difference:
backend = {"Python", "C#", "Java"}
frontend = {"JavaScript", "HTML", "CSS", "Python"}
# Languages in common
print(backend & frontend) # output: {'Python'}
# Union of both sets
print(backend | frontend)
# Backend-only languages
print(backend - frontend)
These operations help a lot, for example, when we need to compare permissions between two user profiles, find intersections between lists of resources, or validate exclusive sets.
In addition, sets are extremely efficient for membership checks. Instead of going through an entire list with in, a set does this in constant time (O(1)):
languages = {"Python", "C#", "Java", "Go"}
if "Python" in languages:
print("Python is present!")
For collections with thousands of elements, this performance gain is significant.
I usually follow these simple rules to decide:
We can also use a frozenset when we need an immutable set. It is less common, but it shows up in cases where sets are used as keys or fixed values.
permissions = frozenset(["read", "write"])
A solid understanding of tuples and sets in Python helps me write cleaner, more efficient, and safer code. Both are part of the foundation of modern Python and appear all the time, whether in libraries, APIs, or internal structures. The sooner you master these two concepts, the better prepared you will be to solve real problems in backend development.
If you want to go deeper, I recommend taking a look at the official documentation for each one:
Web development has evolved significantly in recent years, and Python frameworks are at the forefront…
Artificial intelligence is revolutionizing every sector of society, from enterprise applications to everyday solutions. At…
Among Python's most versatile data structures, dictionaries stand out. They help us represent structured data…
In this ninth lesson of the mini course, I want to talk about one of…
Understanding variable scope in Python is essential to avoid errors and write more predictable programs.…
Functions are one of the most important concepts in any programming language, and Python is…
Este blog utiliza cookies. Se você continuar assumiremos que você está satisfeito com ele.
Leia Mais...