This is a brief documentation on how to use sets in Python.
In Python, a set is a collection – i.e. a container which without indexing and withour order.
Sets are declared with {} brackets in Python
# defining a set with 5 elements a = {"a","b","c","d","e"}
Sets are printable
# printing set a will also show you how they do NOT have any defined order print(a)
{'c', 'e', 'd', 'b', 'a'}
Sets can contain different types of data
# sets can contain different datatypes b = {1,"a",1.1} print(b)
{1, 'a', 1.1}
Sets are iterable
# using for loop to print all elements of set b for i in b: print(i)
1 a 1.1
You can add elements to a set using the .add() method
# adding an element to set b, using .add() method b.add(-111) print(b)
{1, -111, 'a', 1.1}
You can add multiple items to a set, using the .update() method
# adding three new elements to set b, using .update() b.update([1,2,3]) print(b)
{1, 2, 1.1, 3, -111, 'a'}
As with Python lists, the length of a set equals the number of elements and is determined using the len() function
# determining the length of set b len(b)
6
Elements can be removed from a set, using the .remove() method
# removing element with value "a" from set b b.remove("a") print(b)
{1, 2, 1.1, 3, -111}
Sets cannot contain duplicates
# delcaring a set with duplicates; duplicates will be ignored c = {"a","a","a"} # printing set c will show that duplicates have been automatically removed from the set print(c)
{'a'}
.clear() will clear a set from its content
# clearing set b, using .clear() b.clear() print(b)
set()
Empty sets can be declared using set()
# delcaring empty set, using set() constructor d = set() # printing empty set d print(d) # checking type of d, to confirm that it is a set type(d) # add element with value "a" d.add("a") # print set after having added the additional element print(d)
set() {'a'}
A set can be entirely deleted, usign the del keyword
# deleting set d del d # trying to print d; this will return a traceback print(d)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-51-38cd230d9bf2> in <module> 2 del d 3 # trying to print d; this will return a traceback ----> 4 print(d) NameError: name 'd' is not defined
Sets can be joined, using .union()
# defining two new sets, e and f e = {"a","b","c"} f = {1,2,3} # joining the two sets (merging) and printing the merged set print(e.union(f))
{'c', 1, 2, 3, 'b', 'a'}
Other important containers are e.g. Python dictionaries and Python lists.
Data scientist focusing on simulation, optimization and modeling in R, SQL, VBA and Python
Leave a Reply