Skip to main content

Tuples and Sets

In addition to Lists and Dictionaries (which are the most common), Python offers two other very useful native data structures: Tuples and Sets. Knowing them will allow you to choose the right tool for the right job.

Tuples (tuple)

A tuple is an ordered collection and UNLIKE LISTS, UNCHANGEABLE (IMMUTABLE). Once a tuple is created, you cannot change, add, or remove its elements. They are defined using parentheses ().

# Creating a tuple
coordinates = (4.5, 9.1)
primary_colors = ("red", "yellow", "blue")

# Accessing elements (just like in lists)
print(primary_colors[0]) # Output: red

# Trying to modify a tuple (THIS WILL CAUSE AN ERROR)
# coordinates[0] = 5.0 <-- TypeError: 'tuple' object does not support item assignment

When to use Tuples instead of Lists?

  1. To protect data: If you have a collection of values that must not change under any circumstances throughout your program (like days of the week, mathematical constants, configurations), use a tuple.
  2. Performance: Tuples are slightly lighter and faster in memory than lists.
  3. As dictionary keys: Since they are immutable, tuples can be used as "keys" in dictionaries (lists cannot).

Sets (set)

A Set is an unordered, unindexed collection that DOES NOT ALLOW DUPLICATE ELEMENTS. They are defined using curly braces {}, but unlike dictionaries, they do not have a "key:value" structure, only single values.

# Creating a set
fruits = {"apple", "banana", "cherry"}

# Adding elements
fruits.add("orange")

# Sets do not allow duplicates:
numbers = {1, 2, 2, 2, 3, 4, 4}
print(numbers) # Output: {1, 2, 3, 4} (Automatically removes duplicates)

When to use Sets?

  1. To remove duplicates: The fastest way in Python to remove repeated values from a list is to convert it to a set and then back to a list: new_list = list(set(list_with_duplicates)).
  2. For ultra-fast membership checks: If you constantly need to check if an element exists in a giant collection if element in collection, Sets are infinitely faster than lists.
  3. Mathematical set operations: Sets in Python support classic set theory operations like unions (|), intersections (&), and differences (-).
set_a = {1, 2, 3}
set_b = {3, 4, 5}

# Intersection (what they have in common)
print(set_a & set_b) # Output: {3}