Example of Python Sets

Python3




var = {"Geeks", "for", "Geeks"}
type(var)


Output:

set

Time Complexity: O(1)
Auxiliary Space: O(1)

Type Casting with Python Set method

The Python set() method is used for type casting.

Python3




# typecasting list to set
myset = set(["a", "b", "c"])
print(myset)
 
# Adding element to the set
myset.add("d")
print(myset)


Output:

Python set is an unordered datatype, which means we cannot know in which order the elements of the set are stored.

{'c', 'b', 'a'}
{'d', 'c', 'b', 'a'}

Time Complexity: O(n)
Auxiliary Space: O(n)

Check unique and  Immutable with Python Set

Python sets cannot have a duplicate value and once it is created we cannot change its value.

Python3




# Python program to demonstrate that
# a set cannot have duplicate values
# and we cannot change its items
 
# a set cannot have duplicate values
myset = {"Geeks", "for", "Geeks"}
print(myset)
 
# values of a set cannot be changed
myset[1] = "Hello"
print(myset)


Output:

The first code explains that the set cannot have a duplicate value. Every item in it is a unique value. 

The second code generates an error because we cannot assign or change a value once the set is created. We can only add or delete items in the set.

{'Geeks', 'for'}
TypeError: 'set' object does not support item assignment

Heterogeneous Element with Python Set

Python sets can store heterogeneous elements in it, i.e., a set can store a mixture of string, integer, boolean, etc datatypes.

Python3




# Python example demonstrate that a set
# can store heterogeneous elements
myset = {"Geeks", "for", 10, 52.7, True}
print(myset)


Output:

{True, 10, 'Geeks', 52.7, 'for'}

Time Complexity: O(n)
Auxiliary Space: O(n)

Sets in Python

A Set in Python programming is an unordered collection data type that is iterable, mutable and has no duplicate elements. 

Set are represented by { } (values enclosed in curly braces)

The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. This is based on a data structure known as a hash table. Since sets are unordered, we cannot access items using indexes as we do in lists.

Similar Reads

Example of Python Sets

Python3 var = {"Geeks", "for", "Geeks"} type(var)...

Python Frozen Sets

...

Internal working of Set

...

Methods for Sets

...

Time complexity of Sets

...

Operators for Sets

Frozen sets in Python are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied. It can be done with frozenset() method in Python....