Conjunto Python (com exemplos)

Neste tutorial, você aprenderá tudo sobre os conjuntos Python; como eles são criados, adicionando ou removendo elementos deles, e todas as operações realizadas em conjuntos em Python.

Vídeo: conjuntos em Python

Um conjunto é uma coleção não ordenada de itens. Cada elemento definido é único (sem duplicatas) e deve ser imutável (não pode ser alterado).

No entanto, um conjunto em si é mutável. Podemos adicionar ou remover itens dele.

Os conjuntos também podem ser usados ​​para realizar operações matemáticas de conjunto, como união, interseção, diferença simétrica, etc.

Criação de conjuntos Python

Um conjunto é criado colocando todos os itens (elementos) entre chaves (), separados por vírgula, ou usando a set()função embutida.

Ele pode ter qualquer número de itens e eles podem ser de tipos diferentes (inteiro, flutuante, tupla, string etc.). Mas um conjunto não pode ter elementos mutáveis ​​como listas, conjuntos ou dicionários como seus elementos.

 # Different types of sets in Python # set of integers my_set = (1, 2, 3) print(my_set) # set of mixed datatypes my_set = (1.0, "Hello", (1, 2, 3)) print(my_set)

Resultado

 (1, 2, 3) (1.0, (1, 2, 3), 'Olá')

Experimente os exemplos a seguir também.

 # set cannot have duplicates # Output: (1, 2, 3, 4) my_set = (1, 2, 3, 4, 3, 2) print(my_set) # we can make set from a list # Output: (1, 2, 3) my_set = set((1, 2, 3, 2)) print(my_set) # set cannot have mutable items # here (3, 4) is a mutable list # this will cause an error. my_set = (1, 2, (3, 4))

Resultado

 (1, 2, 3, 4) (1, 2, 3) Traceback (última chamada mais recente): Arquivo "", linha 15, em my_set = (1, 2, (3, 4)) TypeError: tipo inalterável: 'Lista'

Criar um conjunto vazio é um pouco complicado.

Chaves ()vazias farão um dicionário vazio em Python. Para fazer um conjunto sem nenhum elemento, usamos a set()função sem nenhum argumento.

 # Distinguish set and dictionary while creating empty set # initialize a with () a = () # check data type of a print(type(a)) # initialize a with set() a = set() # check data type of a print(type(a))

Resultado

 

Modificando um conjunto em Python

Os conjuntos são mutáveis. No entanto, como não são ordenados, a indexação não tem significado.

Não podemos acessar ou alterar um elemento de um conjunto usando indexação ou fatiamento. O tipo de dados definido não é compatível.

Podemos adicionar um único elemento usando o add()método e vários elementos usando o update()método. O update()método pode ter tuplas, listas, strings ou outros conjuntos como seu argumento. Em todos os casos, as duplicatas são evitadas.

 # initialize my_set my_set = (1, 3) print(my_set) # my_set(0) # if you uncomment the above line # you will get an error # TypeError: 'set' object does not support indexing # add an element # Output: (1, 2, 3) my_set.add(2) print(my_set) # add multiple elements # Output: (1, 2, 3, 4) my_set.update((2, 3, 4)) print(my_set) # add list and set # Output: (1, 2, 3, 4, 5, 6, 8) my_set.update((4, 5), (1, 6, 8)) print(my_set)

Resultado

 (1, 3) (1, 2, 3) (1, 2, 3, 4) (1, 2, 3, 4, 5, 6, 8)

Remover elementos de um conjunto

Um item específico pode ser removido de um conjunto usando os métodos discard()e remove().

A única diferença entre os dois é que a discard()função deixa um conjunto inalterado se o elemento não estiver presente no conjunto. Por outro lado, a remove()função gerará um erro em tal condição (se o elemento não estiver presente no conjunto).

O exemplo a seguir ilustrará isso.

 # Difference between discard() and remove() # initialize my_set my_set = (1, 3, 4, 5, 6) print(my_set) # discard an element # Output: (1, 3, 5, 6) my_set.discard(4) print(my_set) # remove an element # Output: (1, 3, 5) my_set.remove(6) print(my_set) # discard an element # not present in my_set # Output: (1, 3, 5) my_set.discard(2) print(my_set) # remove an element # not present in my_set # you will get an error. # Output: KeyError my_set.remove(2)

Resultado

 (1, 3, 4, 5, 6) (1, 3, 5, 6) (1, 3, 5) (1, 3, 5) Traceback (última chamada mais recente): Arquivo "", linha 28, em KeyError: 2

Da mesma forma, podemos remover e retornar um item usando o pop()método.

Como set é um tipo de dados não ordenado, não há como determinar qual item será exibido. É completamente arbitrário.

Também podemos remover todos os itens de um conjunto usando o clear()método.

 # initialize my_set # Output: set of unique elements my_set = set("HelloWorld") print(my_set) # pop an element # Output: random element print(my_set.pop()) # pop another element my_set.pop() print(my_set) # clear my_set # Output: set() my_set.clear() print(my_set) print(my_set)

Resultado

 ('H', 'l', 'r', 'W', 'o', 'd', 'e') H ('r', 'W', 'o', 'd', 'e' ) set ()

Operações de conjunto Python

Os conjuntos podem ser usados ​​para realizar operações matemáticas de conjunto, como união, interseção, diferença e diferença simétrica. Podemos fazer isso com operadores ou métodos.

Vamos considerar os dois conjuntos a seguir para as seguintes operações.

 >>> A = (1, 2, 3, 4, 5) >>> B = (4, 5, 6, 7, 8)

Definir União

Definir união em Python

A união de A e B é um conjunto de todos os elementos de ambos os conjuntos.

A união é realizada usando o |operador. O mesmo pode ser feito usando o union()método.

 # Set union method # initialize A and B A = (1, 2, 3, 4, 5) B = (4, 5, 6, 7, 8) # use | operator # Output: (1, 2, 3, 4, 5, 6, 7, 8) print(A | B)

Resultado

 (1, 2, 3, 4, 5, 6, 7, 8)

Experimente os exemplos a seguir no shell Python.

 # use union function >>> A.union(B) (1, 2, 3, 4, 5, 6, 7, 8) # use union function on B >>> B.union(A) (1, 2, 3, 4, 5, 6, 7, 8)

Definir interseção

Definir interseção em Python

A intersecção de A e B é um conjunto de elementos que são comuns em ambos os conjuntos.

A intersecção é realizada usando o &operador. O mesmo pode ser feito usando o intersection()método.

 # Intersection of sets # initialize A and B A = (1, 2, 3, 4, 5) B = (4, 5, 6, 7, 8) # use & operator # Output: (4, 5) print(A & B)

Resultado

 (4, 5)

Experimente os exemplos a seguir no shell Python.

 # use intersection function on A >>> A.intersection(B) (4, 5) # use intersection function on B >>> B.intersection(A) (4, 5)

Definir diferença

Definir diferença em Python

A diferença do conjunto B do conjunto A (A - B) é um conjunto de elementos que estão apenas em A, mas não em B. Da mesma forma, B - A é um conjunto de elementos em B, mas não em A.

A diferença é realizada usando o -operador. O mesmo pode ser feito usando o difference()método.

 # Difference of two sets # initialize A and B A = (1, 2, 3, 4, 5) B = (4, 5, 6, 7, 8) # use - operator on A # Output: (1, 2, 3) print(A - B)

Resultado

 (1, 2, 3)

Experimente os exemplos a seguir no shell Python.

 # use difference function on A >>> A.difference(B) (1, 2, 3) # use - operator on B >>> B - A (8, 6, 7) # use difference function on B >>> B.difference(A) (8, 6, 7)

Definir diferença simétrica

Definir diferença simétrica em Python

A diferença simétrica de A e B é um conjunto de elementos em A e B, mas não em ambos (excluindo a interseção).

A diferença simétrica é realizada usando o ^operador. O mesmo pode ser feito usando o método symmetric_difference().

 # Symmetric difference of two sets # initialize A and B A = (1, 2, 3, 4, 5) B = (4, 5, 6, 7, 8) # use operator # Output: (1, 2, 3, 6, 7, 8) print(A B)

Resultado

 (1, 2, 3, 6, 7, 8)

Experimente os exemplos a seguir no shell Python.

 # use symmetric_difference function on A >>> A.symmetric_difference(B) (1, 2, 3, 6, 7, 8) # use symmetric_difference function on B >>> B.symmetric_difference(A) (1, 2, 3, 6, 7, 8)

Outros métodos de conjunto Python

There are many set methods, some of which we have already used above. Here is a list of all the methods that are available with the set objects:

Method Description
add() Adds an element to the set
clear() Removes all elements from the set
copy() Returns a copy of the set
difference() Returns the difference of two or more sets as a new set
difference_update() Removes all elements of another set from this set
discard() Removes an element from the set if it is a member. (Do nothing if the element is not in set)
intersection() Returns the intersection of two sets as a new set
intersection_update() Updates the set with the intersection of itself and another
isdisjoint() Returns True if two sets have a null intersection
issubset() Returns True if another set contains this set
issuperset() Returns True if this set contains another set
pop() Removes and returns an arbitrary set element. Raises KeyError if the set is empty
remove() Removes an element from the set. If the element is not a member, raises a KeyError
symmetric_difference() Returns the symmetric difference of two sets as a new set
symmetric_difference_update() Updates a set with the symmetric difference of itself and another
union() Returns the union of sets in a new set
update() Updates the set with the union of itself and others

Other Set Operations

Set Membership Test

We can test if an item exists in a set or not, using the in keyword.

 # in keyword in a set # initialize my_set my_set = set("apple") # check if 'a' is present # Output: True print('a' in my_set) # check if 'p' is present # Output: False print('p' not in my_set)

Output

 True False

Iterating Through a Set

We can iterate through each item in a set using a for loop.

 >>> for letter in set("apple"):… print(letter)… a p e l

Built-in Functions with Set

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used with sets to perform different tasks.

Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns False.
enumerate() Returns an enumerate object. It contains the index and value for all the items of the set as a pair.
len() Returns the length (the number of items) in the set.
max() Returns the largest item in the set.
min() Returns the smallest item in the set.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
sum() Returns the sum of all elements in the set.

Python Frozenset

Frozenset é uma nova classe que tem as características de um conjunto, mas seus elementos não podem ser alterados depois de atribuídos. Enquanto as tuplas são listas imutáveis, os conjuntos de congelamento são conjuntos imutáveis.

Os conjuntos mutáveis ​​são inalteráveis, portanto, não podem ser usados ​​como chaves de dicionário. Por outro lado, os frozensets são hashaveis e podem ser usados ​​como chaves para um dicionário.

Frozensets podem ser criados usando a função frozenset ().

Este tipo de dados suporta métodos como copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference()e union(). Por ser imutável, não possui métodos que adicionam ou removem elementos.

 # Frozensets # initialize A and B A = frozenset((1, 2, 3, 4)) B = frozenset((3, 4, 5, 6))

Experimente estes exemplos no shell Python.

 >>> A.isdisjoint(B) False >>> A.difference(B) frozenset((1, 2)) >>> A | B frozenset((1, 2, 3, 4, 5, 6)) >>> A.add(3)… AttributeError: 'frozenset' object has no attribute 'add'

Artigos interessantes...