A Python set is a collection of unique elements
. Sets are unordered
, which means that the elements of a set do not have a specific order. Sets are also mutable
, which means they can be changed after they are created. To create a set, you can use the set() function
. This function takes an iterable as input and returns a set containing the unique elements of the iterable. For example, the following code creates a set containing the numbers 1, 2, and 3 as well as a string ‘hello and world.
my_set = set([1, 2, 3, "hello", "world"])
print(my_set) # random order output {1, 2, 3, 'hello', 'world'}
I can create a set
from a string
. For example, the following code creates a set containing the individual characters of the string “hello”: ‘h’, ‘e’, ‘l’, ‘o’. The output will be randomized.
my_set = set("hello")
print(my_set) # output {'e', 'h', 'l', 'o'}
Once you have created a set, you can add and remove elements from it using the add()
and remove()
methods. Using the operator, you can also check whether an element is in a set. Sets are useful for a variety of tasks, such as: Removing duplicate elements from a list
: To remove duplicate elements from a list, you can convert it to a set and then back to a list. For example, the following code removes the duplicate elements from the list [1, 2, 3, 10, 10, 3, 1, 4, 2]
:
new_set = [1, 2, 3, 10, 10, 3, 1, 4, 2] # list with duplicate [] This is a list.
print(new_set)
# output {1, 2, 3, 4, 10} remove duplicate
new_set_without_duplicate = set(new_set) # convert list to set
print(new_set_without_duplicate)
# output {1, 2, 3, 4, 10} set {}
new_set_without_duplicate = list(new_set) # convert set to list
print(new_set_without_duplicate)
# output [1, 2, 3, 4, 10] # [] Back to list