Sets are Python objects similar to lists. The main difference is that Python sets, similarly to the mathematical objects, contain only one copy of each element.
Here is how sets are defined:
s1 = {131, 2, 23, 4}
The set s1
will contain just one copy of each element:
s1
The elements in the set won't necessarily be in any particular order. We can check whether an element is in the set like this:
4 in s1
120 in s1
A set can contain any immutable object:
{1, "hi", "EngSci", 100}
We can get a set of all the element in a list like this:
L = [1, 2, 10, 1, 2, 2, 5]
set(L)
Finally, we can iterate through a set like this:
for e in {2, 4, 23, 131}:
print(e)
The main use that we'll see of sets is going through every element in a list without repetition:
for e in set([4, 5, 4, 5, 4, 5, 7, 10]):
print(e)