Sets
Range¶
Python has range built in which allows you to call range(a, b) to get all integers from the integer a up to but not including b. It will be used for more than just lists, but for now we want to understand that calling list(range(a, b)) will return a list where the starting value is the integer a, going up to b-1.
#Get the values from 1 to 10
l = list(range(1,11))
print(l)
Tuples¶
Tuples are similar to lists except for a few differences which include the fact that you can not change the elements in it, they can perform certain operations faster in some cases, and a few other differences. They are declared with parentheses like in the code below.
#Declare a tuple
t = (1,1)
print(t)
We can't change values in a tuple.
#You can't set a value on a tuple
t = (1,1)
t[1] = 0
The functions count, index and the use of indexing all behave the same way.
print(t.count(1))
print(t.index(1))
print(t[0])
Sets¶
Sets are data structures which include only unique values. This can be helpful to remove duplicates. They are declared with curly braces.
#A set gives us unique values
s = {1,2,3}
print(s)
We can convert a list to a set with set(), notice how it makes it to only have the unique values.
#So here we see that the set is only 1, 2, 3 because those are the unique values
l = [1,1,1,2,2,3]
s = set(l)
print(s)
Union and Intersection¶
For sets, there is union which combines two sets (only the unique values) and interaction which returns only values in both sets. Both are done by calling union/intersection on one of the sets and passing the other set as an argument.
#Union joins the unique elements together
s1 = {1,2}
s2 = {2,3}
print(s1.union(s2))
#Intersection finds where they overlap
print(s1.intersection(s2))
Isdisjoint and Remove¶
The function isdisjoint returns true if there are no overlapping values between two sets or false if there is an overlapping value. Remove acts just as we have seen before with other data structures. At first the two sets are not disjoint because s1 has 2 and s2 also has 2. After removing 2 from s1, they are now disjoint.
#They have an overlapping element so they are not disjoint
print(s1.isdisjoint(s2))
#Remove 2 from s1
s1.remove(2)
print(s1)
#But now they are since we got rid of 2 from s1
print(s1.isdisjoint(s2))