Python

Tuples and Sets in Python: When to Use Each One – Lesson 11

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.

What are Tuples?

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: collections without duplicates

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.

When should you use tuples and sets in Python?

I usually follow these simple rules to decide:

  • I use a tuple when:
    • The data has a logical order.
    • I need to guarantee that nothing will be modified.
    • I want to use it as a dictionary key, since tuples are hashable.
    • I need a lighter, faster structure than a list.
  • I use a set when:
    • I need to remove duplicates automatically.
    • I am going to perform mathematical set operations.
    • I want fast membership checks.
    • I don’t need to worry about the order of the items.

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"])

Final thoughts

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:

Vinicius Sodré

Formado em Ciência da Computação pela Unicarioca, desenvolvedor de software com 15 anos de experiência em grandes empresas nacionais e multinacionais. Vinicius está à frente deste blog, feito de desenvolvedor para desenvolvedores de iniciantes a experientes.

Compartilhar
Publicado por:
Vinicius Sodré

Posts Recentes

Python Web Frameworks: A Complete Guide

Web development has evolved significantly in recent years, and Python frameworks are at the forefront…

1 year atrás

Python for AI: Master the Path to Artificial Intelligence

Artificial intelligence is revolutionizing every sector of society, from enterprise applications to everyday solutions. At…

1 year atrás

Dictionaries in Python: Everything You Need to Know – Lesson 10

Among Python's most versatile data structures, dictionaries stand out. They help us represent structured data…

2 years atrás

Lists in Python: Everything You Need to Know – Lesson 9

In this ninth lesson of the mini course, I want to talk about one of…

2 years atrás

Variable Scope in Python: Understand It and Get Rid of Bugs – Lesson 8

Understanding variable scope in Python is essential to avoid errors and write more predictable programs.…

2 years atrás

Functions in Python: How to Create and Use Them Efficiently – Lesson 7

Functions are one of the most important concepts in any programming language, and Python is…

2 years atrás

Este blog utiliza cookies. Se você continuar assumiremos que você está satisfeito com ele.

Leia Mais...