Conjuntos de Python: una introducción visual detallada

Bienvenidos

En este artículo, aprenderá los fundamentos de Conjuntos en Python. Este es un tipo de datos incorporado muy poderoso que puede usar en sus proyectos de Python.

Exploraremos:

  • Qué son los conjuntos y por qué son relevantes para sus proyectos.
  • Cómo crear un set.
  • Cómo comprobar si un elemento está en un conjunto.
  • La diferencia entre sets y frozensets.
  • Cómo operar con conjuntos (en esta parte nos sumergiremos en los conceptos básicos de la teoría de conjuntos).
  • Cómo agregar y eliminar elementos de conjuntos y cómo borrarlos.

¡Vamos a empezar! ⭐️

? Conjuntos en contexto

Permítanme comenzar diciéndoles por qué querrían usar conjuntos en sus proyectos. En matemáticas, un conjunto es una colección de objetos distintos. En Python, lo que los hace tan especiales es el hecho de que no tienen elementos duplicados , por lo que pueden usarse para eliminar elementos duplicados de listas y tuplas de manera eficiente.

Según la documentación de Python:

Python también incluye un tipo de datos para conjuntos . Un conjunto es una colección desordenada sin elementos duplicados. Los usos básicos incluyen pruebas de membresía y eliminación de entradas duplicadas.

❗️Importante: Los elementos de un conjunto deben ser inmutables (no se pueden cambiar). Los tipos de datos inmutables incluyen cadenas, tuplas y números como enteros y flotantes.

? Sintaxis

Para crear un conjunto, comenzamos escribiendo un par de llaves {}y dentro de esas llaves incluimos los elementos del conjunto separados por una coma y un espacio.  

? Sugerencia: Tenga en cuenta que esta sintaxis es diferente de los diccionarios de Python porque no estamos creando pares clave-valor, simplemente incluimos elementos individuales entre llaves {}.

Conjunto()

Alternativamente, podemos usar la función set () para crear un conjunto (ver más abajo).

Para hacer esto, pasaríamos un iterable (por ejemplo, una lista, cadena o tupla) y este iterable se convertiría en un conjunto, eliminando cualquier elemento duplicado.

Este es un ejemplo en IDLE:

# Set >>> {1, 2, 3, 4} {1, 2, 3, 4} # From a list >>> set([1, 2, 3, 4]) {1, 2, 3, 4} # From a tuple >>> set((1, 2, 3, 4)) {1, 2, 3, 4}

? Sugerencia: Para crear un conjunto vacío, debe usar la función set () porque el uso de un conjunto vacío de llaves, como este {}, creará automáticamente un diccionario vacío , no un conjunto vacío.

# Creates a dictionary, not a set. >>> type({})  # This is a set >>> type(set()) 

? Se eliminan los elementos duplicados

Si el iterable que pasa como argumento set()tiene elementos duplicados, se eliminan para crear el conjunto.

Por ejemplo, observe cómo se eliminan los elementos duplicados cuando pasamos esta lista:

>>> a = [1, 2, 2, 2, 2, 3, 4, 1, 4] >>> set(a) {1, 2, 3, 4}

y observe cómo se eliminan los caracteres duplicados cuando pasamos esta cadena:

>>> a = "hhheeelllooo" >>> set(a) {'e', 'l', 'o', 'h'}

? Longitud

Para encontrar la longitud de un conjunto, puede usar la función incorporada len ():

>>> a = {1, 2, 3, 4} >>> b = set(a) >>> len(b) 4

En matemáticas, el número de elementos de un conjunto se denomina " cardinalidad " del conjunto.

? Prueba de membresía

Puede probar si un elemento está en un conjunto con el inoperador:

Esto en un ejemplo:

>>> a = "hhheeelllooo" >>> b = set(a) >>> b {'e', 'l', 'o', 'h'} # Test if the characters 'e' and 'a' are in set b >>> 'e' in b True >>> 'a' in b False

? Conjuntos vs Frozensets

Los conjuntos son mutables, lo que significa que pueden modificarse una vez definidos.

Según la documentación de Python:

El settipo es mutable : el contenido se puede cambiar usando métodos como add()y remove(). Dado que es mutable, no tiene valor hash y no se puede utilizar como clave de diccionario ni como elemento de otro conjunto.

Dado que no pueden contener valores de tipos de datos mutables, si intentamos crear un conjunto que contenga conjuntos como elementos (conjuntos anidados), veremos este error:

TypeError: unhashable type: 'set' 

Este es un ejemplo en IDLE. Observe cómo los elementos que intentamos incluir son conjuntos:

>>> a = {{1, 2, 3}, {1, 2, 4}} Traceback (most recent call last): File "", line 1, in  a = {{1, 2, 3}, {1, 2, 4}} TypeError: unhashable type: 'set'

Frozensets

Para solucionar este problema, tenemos otro tipo de set llamado frozensets.

Son inmutables , entoncesno se pueden cambiar y podemos usarlos para crear conjuntos anidados.

Según la documentación de Python:

El frozensettipo es inmutable y se puede usar con hash; su contenido no se puede modificar una vez creado; por tanto, puede utilizarse como clave de diccionario o como elemento de otro conjunto.

Para crear un conjunto congelado, usamos:

? Consejo: puede crear un conjunto congelado vacío con frozenset().

Este es un ejemplo de un conjunto que contiene dos conjuntos congelados:

>>> a = {frozenset([1, 2, 3]), frozenset([1, 2, 4])} >>> a {frozenset({1, 2, 3}), frozenset({1, 2, 4})}

Tenga en cuenta que no obtenemos ningún error y el conjunto se creó correctamente.

? Introducción a la teoría de conjuntos

Antes de sumergirnos en las operaciones de conjuntos, necesitamos explorar un poco la teoría de conjuntos y los diagramas de Venn. Nos sumergiremos en cada operación de conjunto con su equivalente correspondiente en código Python. Vamos a empezar.

Subsets and Supersets

You can think of a subset as a "smaller portion" of a set. That is how I like to think about it. If you take some of the elements of a set and make a new set with those elements, the new set is a subset of the original set.

It's as if you had a bag full of rubber balls of different colors. If you make a set with all the rubber balls in the bag, and then take some of those rubber balls and make a new set with them, the new set is a subset of the original set.

Let me illustrate this graphically. If we have a set A with the elements 1, 2, 3, 4:

>>> a = {1, 2, 3, 4}

We can "take" or "select" some elements of a and make a new set called B. Let's say that we chose to include the elements 1 and 2 in set B:

>>> a = {1, 2, 3, 4} >>> b = {1, 2}

Every element of B is in A. Therefore, B is a subset of A.

This can be represented graphically like this, where the new set B is illustrated in yellow:

? Note: In set theory, it is a convention to use uppercase letters to denote sets. This is why I will use them to refer to the sets (A and B), but I will use lowercase letter in Python (a and b).

.issubset()

We can check if B is a subset of A with the method .issubset():

>>> a = {1, 2, 3, 4} >>> b = {1, 2} >>> b.issubset(a) True

As you can see, B is a subset of A because the value returned is True.

But the opposite is not true since not all the element of A are in B:

>>> a.issubset(b) False

Let's see something very interesting:

>>> a = {1, 2, 3, 4} >>> b = {1, 2, 3, 4} >>> a.issubset(b) True >>> b.issubset(a) True

If two sets are equal, one is a subset of the other and vice versa because all the elements of A are in B and all elements of B are in A. This can be illustrated like this:

Using <=

We can achieve the same functionality of the .issubset() method with the <= comparison operator:

>>> a = {1, 2, 3, 4} >>> b = {1, 2, 3, 4} >>> a <= b True

This operator returns True if the left operand is a subset of the right operand, even when the two sets are equal (when they have the same elements).

Proper Subset

But what happens if we want to check if a set is a proper subset of another? A proper subset is a subset that is not equal to the set (does not have all the same elements).

This would be a graphical example of a proper subset. B does not have all the elements of A:

To check this, we can use the < comparison operator:

# B is not a proper subset of A because B is equal to A >>> a = {1, 2, 3, 4} >>> b = {1, 2, 3, 4} >>> b >> a = {1, 2, 3, 4} >>> b = {1, 2} >>> b < a True

Superset

If B is a subset of A, then A is a superset of B. A superset is the set that contains all the elements of the subset.  

This can be illustrated like this (see below), where A is a superset of B:

.issuperset()

We can test if a set is a superset of another with the .issuperset() method:

>>> a = {1, 2, 3, 4} >>> b = {1, 2} >>> a.issuperset(b) True

We can also use the operators > and >=. They work exactly like < and <=, but now they determine if the left operand is a superset of the right operand:

>>> a = {1, 2, 3, 4} >>> b = {1, 2} >>> a > b True >>> a >= b True

Disjoint Sets

Two sets are disjoint if they have no elements in common. For example, here we have two disjoint sets:

.isdisjoint()

We can check if two sets are disjoint with the .isdisjoint() method:

# Elements in common: 3, 1 >>> a = {3, 6, 1} >>> b = {2, 8, 3, 1} >>> a.isdisjoint(b) False # Elements in common: None >>> a = {3, 1, 4} >>> b = {8, 9, 0} >>> a.isdisjoint(b) True

? Set Operations

We can operate on sets to create new sets, following the rules of set theory. Let's explore these operations.

Union

This is the first operation that we will analyze. It creates a new set that contains all the elements of the two sets (without repetition).

This is an example:

>>> a = {3, 1, 7, 4} >>> b = {2, 8, 3, 1} >>> a | b {1, 2, 3, 4, 7, 8}

? Tip: We can assign this new set to a variable, like this:

>>> a = {3, 1, 7, 4} >>> b = {2, 8, 3, 1} >>> c = a | b >>> c {1, 2, 3, 4, 7, 8}

In a diagram, these sets could be represented like this (see below). This is called a Venn diagram, and it is used to illustrate the relationships between sets and the result of set operations.

We can easily extend this operation to work with more than two sets:

>>> a = {3, 1, 7, 4} >>> b = {2, 8, 3, 1} >>> c = {1, 0, 4, 6} >>> d = {8, 2, 6, 3} # Union of these four sets >>> a | b | c | d {0, 1, 2, 3, 4, 6, 7, 8}

? Tip: If the union contains repeated elements, only one is included in the final set to eliminate repetition.

Intersection

The intersection between two sets creates another set that contains all the elements that are inboth A and B.

This is an example:

>>> a = {3, 6, 1} >>> b = {2, 8, 3, 1} >>> a & b {1, 3}

The Venn diagram for the intersection operation would be like this (see below), because only the elements that are in both A and B are included in the resulting set:

We can easily extend this operation to work with more than two sets:

>>> a = {3, 1, 7, 4, 5} >>> b = {2, 8, 3, 1, 5} >>> c = {1, 0, 4, 6, 5} >>> d = {8, 2, 6, 3, 5} # Only 5 is in a, b, c, and d. >>> a & b & c & d {5}

Difference

The difference between set A and set B is another set that contains all the elements of set A that are not in set B.

This is an example:

>>> a = {3, 6, 1} >>> b = {2, 8, 3, 1} >>> a - b {6}

The Venn diagram for this difference would be like this (see below), because only the elements of A that are not in B are included in the resulting set:

? Tip: Notice how we remove the elements of A that are also in B (in the intersection).

We can easily extend this to work with more than two sets:

>>> a = {3, 1, 7, 4, 5} >>> b = {2, 8, 3, 1, 5} >>> c = {1, 0, 4, 6, 5} # Only 7 is in A but not in B and not in C >>> a - b - c {7}

Symmetric Difference

The symmetric difference between two sets A and B is another set that contains all the elements that are in either A or B, but not both. We basically remove the elements from the intersection.

>>> a = {3, 6, 1} >>> b = {2, 8, 3, 1} >>> a ^ b {2, 6, 8}

The Venn diagram for the symmetric difference would be like this (see below), because only the elements that are in either A or B, but not both, are included in the resulting set:

We can easily extend this to work with more than two sets:

>>> a = {3, 1, 7, 4, 5} >>> b = {2, 8, 3, 1, 5} >>> c = {1, 0, 4, 6, 5} >>> d = {8, 2, 6, 3, 5} >>> a ^ b ^ c ^ d {0, 1, 3, 7}

Update Sets Automatically

If you want to update set A immediately after performing these operations, you can simply add an equal sign after the operator. For example:

>>> a = {1, 2, 3, 4} >>> b = {1, 2} # Notice the &= >>> a &= b >>> a {1, 2}

We are assigning the set that results from a & b to set a in just one line. You can do the same with the other operators: ^= , |=, and -=.

? Tip: This is very similar to the syntax that we use with variables (for example: a += 5) but now we are working with sets.

? Set Methods

Sets include helpful built-in methods to help us perform common and essential functionality such as adding elements, deleting elements, and clearing the set.

Add Elements

To add elements to a set, we use the .add() method, passing the element as the only argument.

>>> a = {1, 2, 3, 4} >>> a.add(7) >>> a {1, 2, 3, 4, 7}

Delete Elements

There are three ways to delete an element from a set: .remove() ,.discard(), and .pop(). They have key differences that we will explore.

The first two methods (.remove() and .discard()) work exactly the same when the element is in the set. The new set is returned:

>>> a = {1, 2, 3, 4} >>> a.remove(3) >>> a {1, 2, 4} >>> a = {1, 2, 3, 4} >>> a.discard(3) >>> a {1, 2, 4}

The key difference between these two methods is that if we use the .remove() method, we run the risk of trying to remove an element that doesn't exist in the set and this will raise a KeyError:

>>> a = {1, 2, 3, 4} >>> a.remove(5) Traceback (most recent call last): File "", line 1, in  a.remove(5) KeyError: 5

We will never have that problem with .discard() since it doesn't raise an exception if the element is not found. This method will simply leave the set intact, as you can see in this example:

>>> a = {1, 2, 3, 4} >>> a.discard(5) >>> a {1, 2, 3, 4}

The third method (.pop()) will remove and return an arbitrary element from the set and it will raise a KeyError if the set is empty.

>>> a = {1, 2, 3, 4} >>> a.pop() 1 >>> a.pop() 2 >>> a.pop() 3 >>> a {4} >>> a.pop() 4 >>> a set() >>> a.pop() Traceback (most recent call last): File "", line 1, in  a.pop() KeyError: 'pop from an empty set'

Clear the Set

You can use the .clear() method if you need to delete all the elements from a set. For example:

>>> a = {1, 2, 3, 4} >>> a.clear() >>> a set() >>> len(a) 0

? In Summary

  • Sets are unordered built-in data types that don't have any repeated elements, so they allow us to eliminate repeated elements from lists and tuples.
  • They are mutable and they can only contain immutable elements.
  • We can check if a set is a subset or superset of another set.
  • Frozenset is an immutable type of set that allows us to create nested sets.
  • We can operate on sets with: union (|), intersection (&), difference (-), and symmetric difference (^).
  • We can add elements to a set, delete them, and clear the set completely using built-in methods.

I really hope you liked my article and found it helpful. Now you can work with sets in your Python projects. Check out my online courses. Follow me on Twitter. ⭐️