Why Python:
QUESTION 1
how do you access the last element of the tuple: A=(0,1,2,3)
:
A=(0,1,2,3)
A[3]
A[-1]
QUESTION 2 (1 point possible)
Consider the list
B=["a","b","c"]
what is the result of the following B[1:]
B=["a","b","c"]
B[1:]
B[:1]
B[1]
B[:2]
B[2:]
# B[Start:End]
Imagine you received album recommendations from your friends and compiled all of the recomendations into a table, with specific information about each album.
The table has one row for each movie and several columns:
The dataset can be seen below:
<table font-size:xx-small style="width:25%">
<img src = "https://ibm.box.com/shared/static/t2jw5ia78ulp8twr71j6q7055hykz10c.png" width = 750, align = "center"></a>
tuple1=("disco",10,1.2 )
tuple1
tuple1=("disco",10,1.2 )
tuple1
The type of variable is a tuple.
type(tuple1)
Each element of a tuple can be accessed via an index. The following table represents the relationship between the index and the items in the tuple. Each element can be obtained by the name of the tuple followed by a square bracket with the index number:
<img src = "https://ibm.box.com/shared/static/83kpang0opwen5e5gbwck6ktqw7btwoe.gif" width = 750, align = "center"></a>
We can print out each value in the tuple:
print( tuple1[0])
print( tuple1[1])
print( tuple1[2])
We can print out the type of each value in the tuple:
print( type(tuple1[0]))
print( type(tuple1[1]))
print( type(tuple1[2]))
We can also use negative indexing. We use the same table above with corresponding negative values:
<img src = "https://ibm.box.com/shared/static/uwlfzo367bekwg0p5s5odxlz7vhpojyj.png" width = 750, align = "center"></a>
We can obtain the last element as follows (this time we will not use the print statement to display the values):
tuple1[-1]
We can display the next two elements as follows:
tuple1[-2]
tuple1[-3]
We can concatenate or combine tuples by using the + sign:
tuple2=tuple1+("hard rock", 10)
tuple2
We can slice tuples obtaining multiple values as demonstrated by the figure below:
<img src = "https://ibm.box.com/shared/static/s9nofy728bcnsgnx3vh159bu16w7frnc.gif" width = 750, align = "center"></a>
We can slice tuples, obtaining new tuples with the corresponding elements:
tuple2[0:3]
We can obtain the last two elements of the tuple:
tuple2[3:5]
We can obtain the length of a tuple using the length command:
len(tuple2)
This figure shows the number of elements:
<img src = "https://ibm.box.com/shared/static/apxe8l3w42f597yjhizg305merlm4ijf.png" width = 750, align = "center"></a>
Consider the following tuple:
Ratings =(0,9,6,5,10,8,9,6,2)
We can assign the tuple to a 2nd variable:
Ratings1=Ratings
Ratings
We can sort the values in a tuple and save it to a new tuple:
RatingsSorted=sorted(Ratings )
RatingsSorted
A tuple can contain another tuple as well as other more complex data types. This process is called 'nesting'. Consider the following tuple with several elements:
NestedT =(1, 2, ("pop", "rock") ,(3,4),("disco",(1,2)))
The following figure shows the relationship of the tree and the element NestedT[4][1][1]:
<img src ='https://ibm.box.com/shared/static/9y5s7515zwzc9v6i4f67yj3np2fv9evs.gif' width = 750, align = "center"></a>
Consider the following tuple:
genres_tuple = ("pop", "rock", "soul", "hard rock", "soft rock", \
"R&B", "progressive rock", "disco")
genres_tuple
len(genres_tuple)
genres_tuple[3]
genres_tuple[3:6]
genres_tuple[0:2]
genres_tuple.index("disco")
C_tuple = (-5,1,-3)
C_list = sorted(C_tuple)
C_list
Imagine you received many music recommendations from your friends and compiled all of the recommendations into a table, with specific information about each movie.
The table has one row for each album and several columns:
The dataset can be seen below:
<table font-size:xx-small style="width:25%">
To create a list, type the list within square brackets [ ], with your content inside the parenthesis and separated by commas. Let’s try it!
L=["Michael Jackson" , 10.1,1982]
L
We can use negative and regular indexing with a list :
print('the same element using negative and positive indexing:\n Postive:',L[0],
'\n Negative:' , L[-3] )
print('the same element using negative and positive indexing:\n Postive:',L[1],
'\n Negative:' , L[-2] )
print('the same element using negative and positive indexing:\n Postive:',L[2],
'\n Negative:' , L[-1] )
Lists can contain strings, floats, and integers. We can nest other lists, and we can also nest tuples and other data structures. The same indexing conventions apply for nesting:
[ "Michael Jackson", 10.1,1982,[1,2],("A",1) ]
We can also perform slicing in lists. For example, if we want the last two elements, we use the following command:
L=[ "Michael Jackson", 10.1,1982,"MJ",1]
L
L[3:5]
We can use the method "extend" to add new elements to the list:
L=[ "Michael Jackson", 10.2]
L.extend(['pop',10])
L
Another similar method is 'appended'. If we apply 'appended' instead of 'extended', we add one element to the list:
L=[ "Michael Jackson", 10.2]
L.append(['pop',10])
L
Each time we apply a method, the list changes. If we apply "extend" we add two new elements to the list. The list L is then modified by adding two new elements:
L=[ "Michael Jackson", 10.2]
L.extend(['pop',10])
L
If we append the list ['a','b'] we have one new element consisting of a nested list:
L.append(['a','b'])
L
As lists are mutable, we can change them. For example, we can change the first element as follows:
A=["disco",10,1.2]
print('Before change:', A)
A[0]='hard rock'
print('After change:', A)
We can also delete an element of a list using the del command:
print('Before change:', A)
del(A[0])
print('After change:', A)
We can convert a string to a list using 'split'. For example, the method split translates every group of characters separated by a space into an element in a list:
'hard rock'.split()
We can use the split function to separate strings on a specific character. We pass the character we would like to split on into the argument, which in this case is a comma. The result is a list, and each element corresponds to a set of characters that have been separated by a comma:
'A,B,C,D'.split(',')
When we set one variable B equal to A; both A and B are referencing the same list in memory :
A=["hard rock",10,1.2]
B=A
print('A:',A)
print('B:',B)
Initially, the value of the first element in B is set as hard rock. If we change the first element in A to 'banana', we get an unexpected side effect. As A and B are referencing the same list, if we change list A, then list B also changes. If we check the first element of B we get banana instead of hard rock:
print('B[0]:',B[0])
A[0]="banana"
print('B[0]:',B[0])
This is demonstrated in the following figure:
You can clone list A by using the following syntax:
B=A[:]
B
Variable B references a new copy or clone of the original list; this is demonstrated in the following figure:
Now if you change A, B will not change:
print('B[0]:',B[0])
A[0]="banana"
print('B[0]:',B[0])
a_list=[1, 'hello', [1,2,3 ] , True]
a_list
a_list[1]
a_list[1:3]
A=[1,'a']
B=[2,1,'d']
A+B
QUICK PRACTICE LAB
QUESTION 1
What is the result of the following lines of code:
S={'A','B','C'}
U={'A','Z','C'}
U.union(S)
QUESTION 2
What is the intersection of set S
and U
S={'A','B','C'}
U={'A','Z','C'}
S.intersection(U)
set1={"pop", "rock", "soul", "hard rock", "rock", "R&B", "rock", "disco"}
set1
The process of mapping is illustrated in the figure:
You can also create a set from a list as follows:
album_list =[ "Michael Jackson", "Thriller", 1982, "00:42:19", \
"Pop, Rock, R&B", 46.0, 65, "30-Nov-82", None, 10.0]
album_set = set(album_list)
album_set
Now let us create a set of genres:
music_genres = set(["pop", "pop", "rock", "folk rock", "hard rock", "soul", \
"progressive rock", "soft rock", "R&B", "disco"])
music_genres
set(['rap','house','electronic music','rap'])
Notice that the duplicates are removed and the output is sorted.
Let us get the sum of the claimed sales:
A=[1,2,2,1]
B=set([1,2,2,1])
print("the sum of A is:",sum(A))
print("the sum of B is:",sum(B))
Now let's determine the average rating:
sum(A)/len(A)
sum(B)/len(B)
Let us go over Set Operations, as these can be used to change the set. Consider the set A:
A = set(["Thriller","Back in Black", "AC/DC"] )
A
We can add an element to a set using the add() method:
A.add("NSYNC")
A
If we add the same element twice, nothing will happen as there can be no duplicates in a set:
A.add("NSYNC")
A
We can remove an item from a set using the remove method:
A.remove("NSYNC")
A
We can verify if an element is in the set using the in command :
"AC/DC" in A
Remember that with sets you can check the difference between sets, as well as the symmetric difference, intersection, and union:
Consider the following two sets:
album_set1 = set(["Thriller",'AC/DC', 'Back in Black'] )
album_set2 = set([ "AC/DC","Back in Black", "The Dark Side of the Moon"] )
album_set1, album_set2
As both sets contain 'AC/DC' and 'Back in Black' we represent these common elements with the intersection of two circles.
We can find the common elements of the sets as follows:
album_set_3=album_set1 & album_set2
album_set_3
We can find all the elements that are only contained in album_set1 using the difference method:
album_set1.difference(album_set2)
We only consider elements in album_set1; all the elements in album_set2, including the intersection, are not included.
The difference between album_set2 and album_set1 is given by:
album_set2.difference(album_set1)
We can also find the intersection, i.e in both album_list2 and album_list1, using the intersection command :
album_set1.intersection(album_set2)
This corresponds to the intersection of the two circles:
The union corresponds to all the elements in both sets, which is represented by colouring both circles:
The union is given by:
album_set1.union(album_set2)
And you can check if a set is a superset or subset of another set, respectively, like this:
set(album_set1).issuperset(album_set2)
set(album_set2).issubset(album_set1)
Here is an example where issubset() is issuperset() is true:
set({"Back in Black", "AC/DC"}).issubset(album_set1)
album_set1.issuperset({"Back in Black", "AC/DC"})
album_set3=album_set1.union(album_set2)
album_set3
album_set1.issubset(album_set3)
QUICK PRACTICE LAB
QUESTION 1 (1 point possible) Consider the following dictionary:
D={'a':0,'b':1,'c':2}
What is the result of the following: D.values()
D={'a':0,'b':1,'c':2}
D.values()
QUESTION 2
Consider the following dictionary:
D={'a':0,'b':1,'c':2}
What is the output of the following D['b']
:
D={'a':0,'b':1,'c':2}
D['b']
A dictionary consists of keys and values. It is helpful to compare a dictionary to a list. Instead of the numerical indexes such as a list, dictionaries have keys. These keys are labels that are used to access values within a dictionary.
An example of a Dictionary Dict:
Dict={"key1":1,"key2":"2","key3":[3,3,3],"key4":(4,4,4),('key5'):5,(0,1):6}
Dict
The keys can be strings:
Dict["key1"]
Keys can also be any immutable object such as a tuple:
Dict[(0,1)]
Each key is separated from its value by a colon ":". Commas separate the items, and the whole dictionary is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this "{}".
release_year_dict = {"Thriller":"1982", "Back in Black":"1980", \
"The Dark Side of the Moon":"1973", "The Bodyguard":"1992", \
"Bat Out of Hell":"1977", "Their Greatest Hits (1971-1975)":"1976", \
"Saturday Night Fever":"1977", "Rumours":"1977"}
release_year_dict
In summary, like a list, a dictionary holds a sequence of elements. Each element is represented by a key and its corresponding value. Dictionaries are created with two curly braces containing keys and values separated by a colon. For every key, there can only be a single value, however, multiple keys can hold the same value. Keys can only be strings, numbers, or tuples, but values can be any data type.
It is helpful to visualize the dictionary as a table, as in figure 9. The first column represents the keys, the second column represents the values.
You will need this dictionary for the next two questions :
soundtrack_dict = { "The Bodyguard":"1992", "Saturday Night Fever":"1977"}
soundtrack_dict
#The Keys "The Bodyguard" and "Saturday Night Fever"
#The values are "1992" and "1977"
You can retrieve the values based on the names:
release_year_dict['Thriller']
This corresponds to:
Similarly for The Bodyguard
release_year_dict['The Bodyguard']
Now let us retrieve the keys of the dictionary using the method release_year_dict():
release_year_dict.keys()
You can retrieve the values using the method values()
:
release_year_dict.values()
We can add an entry:
release_year_dict['Graduation']='2007'
release_year_dict
We can delete an entry:
del(release_year_dict['Thriller'])
del(release_year_dict['Graduation'])
release_year_dict
We can verify if an element is in the dictionary:
'The Bodyguard' in release_year_dict
album_sales_dict= { "The Bodyguard":50, "Back in Black":50,"Thriller":65}
album_sales_dict["Thriller"]
album_sales_dict.keys()
album_sales_dict.values()