Questions from last lecture (10 minutes)
Sets (15 minutes)
Tuples (15 minutes)
Dictionaries (15 minutes)
Questions (5 minutes)
Sets describe an unordered collection of unique objects.
They filter out repeated items.
A Set is created using curly brackets {}
my_l = [5, 9.4, "car", True, "car"]
my_l
my_set = {5, 9.4, "car", True, "car"}
print(my_set)
type(my_set)
set() method as well# Imagine we have the follwoing list, we can convert it to a set
# NOTICE: repeated items are ignored
my_list = [1, 2, 3, 4, 1, 5, 5, 2, 3, 6, 7]
set(my_list)
Sets are known for some operations such as intersection, union, difference and symmetric difference# let's declare two sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Union
a1 = set1 | set2
print("a1:", a1)
a2 = set1.union(set2)
print("a2:", a2)
# intersection
a1 = set1 & set2
print("a1:", a1)
a2 = set1.intersection(set2)
print("a2:", a2)
# difference
a1 = set1 - set2
print(a1)
a2 = set1.difference(set2)
print(a2)
set2.difference(set1)
# symmetric difference
a1 = set1 ^ set2
print(a1)
a2 = set1.symmetric_difference(set2)
print(a2)
Other methods include add(), remove(), et cetera.
See the sets notebook for more methods.
A tuple is very similar to a list.
It can store a sequence of arbitrary objects (a mix of numbers, strings, lists, other tuples, etc.).
Tuples use parentheses ()
# tuple with 3 entries
my_tuple = (1, "a", None, ['a', 'b'], {1,2,3})
print(type(my_tuple))
isinstance(my_tuple, tuple)
Tuples are immutable meaning that once they are created, they cannot be changed.# Lists are mutabale
example_list = [1, "hi", None]
example_list[0] = 2
example_list
# Tuples are immutable
example_tuple = (1, "hi", None)
example_tuple[0] = 2 # TypeError: 'tuple' object does not support item assignment
example_tuple
tuple() to convert any other iterable to a tuple# This is a list
a = [1, "hi", None]
print(type(a))
# Now it is a tuple
b = tuple(a)
print(type(b))
# get an item by a postive index
a = (1, "hi", "45", "ma", 34)
a[2]
# get an item by a negative index
a = (1, "hi", "45", "ma", 34)
a[-1]
# get a subsequence by identifying start-index and stop-index
a = (1, "hi", "45", "ma", 34)
a[0:3]
# get a subsequence after 2 index
# (Notice the 2 index will be included)
a = (1, "hi", "45", "ma", 34)
a[2:]
# get a subsequence before 2 index
# (Notice the 2 index will NOT be included)
a = (1, "hi", "45", "ma", 34)
a[:2]
# get a subsequence before -2 index
# (Notice the 2 index will be included)
a = (1, "hi", "45", "ma", 34)
a[-2:]
# get a subsequence before 2 index
# (Notice the 2 index will NOT be included)
a = (1, "hi", "45", "ma", 34)
a[:-2]
# Now if we can use seq[start, stop, step]
# a = (1, "hi", "45", "ma", 34)
# a[0:2:1]
a = (1, "hi", "45", "ma", 34)
a[::-1]
This is a very importat feature about tuple assignment.
This feature assigns the right-hand side of values into the left-hand side.
In packing: values are included into a new tuple.
In unpacking: those values are extracted into a single variable.
shamiso = "cars"
shamiso
jeffery = "Gardians of the Galaxy: Falling 3"
jeffery
qasim = "Kung Fu Panda"
qasim
# movies is a variable that we assign a tuple of strings to.
### PACKED TUPLE
movies = ("cars", "Gardians of the Galaxy: Falling 3", "Kung Fu Panda")
len(movies)
# UNPACK THE TUPLE
shamiso, jeffery, qasim, ronald = movies
our_class = (["Shamiso", "cars"], ["Jeffery", "Gardians of the Galaxy: Falling 3"], ["Qasim", "Kung Fu Panda"])
type(our_class)
shamiso, jeffery, qasim = our_class
print(shamiso)
print()
print(jeffery)
print()
print(qasim)
type(shamiso)
jeffery = ['Jeffery', 'Gardians of the Galaxy: Falling 3']
jeffery
# packing values
example_tuple = ("John Thomas", 1980, "3 idiots", "xx")
#len(example_tuple)
# unpacking values
name, year, movie, xx = example_tuple
# # print name
print(name)
# # print year
print(year)
# # print movie
print(movie)
xx
#
cling_class = (["Jingyang", "Ronald"], ["Kung Fu Panda", "Wall-E"])
people, movies = cling_class
print(people)
print(movies)
# print("Claire likes the green book")
cling_class[0][0]
f"{cling_class[0][0]} likes {cling_class[1][0]}"
f"{cling_class[0][1]} likes {cling_class[1][1]}"
Dictionaries store key-value pairs. Keys allow us to quickly retrieve values.
Each key maps to one value.
I will create a dictionary that includes information about a person.
| Key | Value |
|---|---|
| name | Derek John |
| age | 35 |
| hobbies | ['swimming', 'diving', 'running'] |
| movies | ('John Wick', 'The Shawshank Redemption', 'Ex Machina') |
we create a dictionary by mapping the key to its value separated by a comma in curly brackets {}
my_dictionary = {"key":"value"}
{key1:value1, key2:value2, ...}
# we create a dictionary by mapping the key to its value
my_dictionary = {"name": "Derek John", "age": 35}
print(my_dictionary)
type(my_dictionary)
# Another way of creating a dictionary is using list of tuples
# inside `dict()`
my_dict = dict([("name", "Derek John"),("age", 35)])
my_dict
Now we add hobbies and movies in the table above to our dictionary
We do this by the following syntax: my_dictionary[new_key] = new_value
Or using update() method.
# First Option
my_dictionary['hobbies'] = ['swimming', 'diving', 'running']
my_dictionary
# Second Option using update()
my_dictionary.update([("movies", ('John Wick', 'The Shawshank Redemption', 'Ex Machina'))])
my_dictionary
# declair empty dict
my_dict = {} # dict()
my_dict
my_dict['names'] = ["Qasim", "Ronald", "Jeffery", "Shamiso", "Jingyang"]
my_dict
my_dict['age'] = (23, 46, 47, 65, 122)
my_dict
# let's find all the movies that Derek watches
my_dict['names']
# let's get his age
my_dict['age']
'name' in my_dictionary
len()¶len(my_dictionary)
keys()¶my_dictionary.keys()
list(my_dictionary.keys())
values()¶my_dictionary.values()
list(my_dictionary.values())
items()¶# get dict items
my_dictionary.items()
# convert them to a list of tuples
list(my_dictionary.items())
# access the first tuple or the tuple at index 0
dict_items = list(my_dictionary.items())
dict_items[0]
# access the second tuple or the tuple at index 1
dict_items[1]
# # access the second item in the tuple
dict_items[1][1]