Free eBook Level 2 Data Structure
Free eBook Level 2 Data Structure
list1 = [1,2,3,4,5]
list2 = [“a”,”b”,”c”,”d”]
Lists
new_list = []
new_list_2 = [3,6,9,12]
Index 0 1 2 3 4 5 6 7 8
[1, 2, 3, 4, 5, 6, 7, 8, 9]
-9 -8 -7 -6 -5 -4 -3 -2 -1 Index
LIST INDEXES
4
>>> testlist[-2]
8
● To refer to a range of the indexes, type the name of the list
followed by the start and end index number separated by
a semicolon within square brackets.
>>> testlist[5:]
[6, 7, 8, 9]
Index 0 1 2 3 4
[1, 2, 3, 4, 5]
-5 -4 -3 -2 -1 Index
LIST INDEXES
>>> print(list1[0])
1
>>> print(list1[3])
4
>>> print(list1[-1])
5
Index 0 1 2 3 4
[1, 2, 3, 4, 5]
-5 -4 -3 -2 -1 Index
LIST INDEXES
>>> print(list1[2:4])
[3,4]
>>> print(list1[2:])
[3,4,5]
>>> print(list1[:2])
[1,2]
>>> print(list1[:])
[1,2,3,4,5]
To get the length of a list, use the function len(list) to count the number of
elements in a list.
LENGTH OF A LIST
You can also use the function del list[index] placing the index of the element
you would like to remove within the brackets.
>>> print(list1)
[1,2,3,5]
To add another list to your current list, use the function
list.extend(list2)placing the name of the list you would like to join
within the brackets.
ADDING LISTS
This allows you to create a new list. This is different from list.extend()
which changes the list being joined to.
INSERTING LIST ELEMENTS
index value
>>> print(list1)
[1, 2, 3, 54, 4, 5]
REVERSING LISTS You can reverse the order of a list using list.reverse, as seen below
[3,4]
>>> list1[1][0]
3
CHALLENGE: Using list1, print [5, 6]. Then try printing 5 from list1.
Code out the appropriate list operations to find the desired output.
1. Use len to calculate the length of the list with the most elements.
EXERCISE
2.
>>> ls00.append(16) OR >>> ls00.insert(15,16)
EXERCISE
3. >>> ls01.reverse()
6. Find the sum of the odd numbers in ls00 and ls02 separately, by calling
their indexes.
>>> odd_sum00 = ls00[-2] + ls00[-4] + ls00[-6]
>>> odd_sum00
39
>>> odd_sum01 = ls01[-1][-2] + ls01[-2][0] + ls01[-2][2]
>>> odd_sum01
45
To sort a list, use the function list.sort() or sorted() to arrange the elements in
ascending order. They will be arranged in increasing order if the elements
are numbers and will be arranged alphabetically if the elements are strings.
SORTING A LIST
2]
>>> list3.sort()
TypeError: '<' not supported between instances of 'int' and
'str'
We can also sort the list according to the second value in each nested list by
changing the key, which determines how the list is sorted. We will use a
function to look at the second value in the list.
Sorting nested lists
>>> list1.sort()
[1, 2, 3, 4, 5]
>>> string1.sort()
AttributeError: 'str' object has no attribute 'sort'
>>> sorted(list1)
[1, 2, 3, 4, 5]
>>> sorted(string1)
['a', 'a', 'b', 'b', 'i', 'l', 'r', 't', 'y', 'z']
list.sort() changes the original list while sorted() retains the original list
LIST.SORT() AND SORTED()
●
and creates a new sorted list
DIFFERENCE BETWEEN
>>> list1.sort()
[1, 2, 3, 4, 5]
>>> list1
[1, 2, 3, 4, 5]
>>> sorted(list2)
[0, 1, 4, 6, 9]
>>> list2
[9, 4, 6, 0, 1]
LIST MULTIPLICATION Similar to strings, lists can also be multiplied.
teamlist.sort(reverse = True)
Code out the instructions given to get the desired outputs
using the following lists.
mylist = [ [ 1, 2] , [3, 4] , [8, 0]]
QUICK CHECK!
code output
code output
Sort mylist by the second values [[3, 4], [1, 2],[8, 0]]
of each sublist, in descending
order.
Insert [5,6] between [3,4] and [[1, 2],[3, 4],[5, 6],[8, 0], 9]
[8,0]. Then put 9 at the end of
the new list. Print the new list.
● Creating a new
dictionary
DICTIONARY ● Dictionary Indexes
● Adding key-value pairs
An array with data (each containing a key paired with a value, known as a
key-value pair) separated by a comma, denoted with { }.
dictionary0 = {}
DICTIONARY
To see what keys and values are in the dictionary, type .keys() or .values()
after the dictionary name.
>>> squares.keys()
dict_keys([1, 2, 3, 4, 5])
>>> squares.values()
dict_values([1, 4, 9, 16, 25])
ADDING KEY-VALUE PAIRS To add a key-value pair, assign a value to a key for the dictionary.
>>> squares[6] = 36
>>> print(squares)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
You can change dictionary values.
CHANGING KEYS AND
squares = {1:1, 2: 4, 3:9, 4:16, 5:25}
del squares
print(squares) #==> NameError: name 'squares'
is not defined
LENGTH OF A DICTIONARY To get the length of a dictionary, use the function len(dict1) to count the
number of key-value pairs in the dictionary.
“Singaporean”}
Now try to print one of the values by calling the dictionary key!
2018 Company Profits
Quarter Profits
1. Create a dictionary called profits with the information above. The key will be the quarter (Q1,
Q2…) and the value will be the profit for that quarter.
2. Find the monthly average for each quarter, and for the year. Which quarter(s) are below
average?
3. In November, an employee was arrested for embezzling $350,000 from the month’s profits.
This money should be added back into profits. Update profits with the correct quarterly
profits.
4. Create a new dictionary called fin_summ with the new monthly averages for each quarter, to
the nearest dollar. Use int(number) or round(number) to round your numbers.
1. Create a dictionary called profits with the information above. The key will be the
quarter (Q1, Q2…) and the value will be the profit for that quarter.
q3_ave = int(profits["Q3"] / 3)
q4_ave = int(profits["Q4"] / 3)
y_ave = int((profits[“Q1”] + profits[“Q2] + profits[“Q3”] +
profits[“Q4”])/12)
profits[“Q4”] += 350000
4. Create a dictionary called fin_summ with the new monthly averages for each
quarter, to the nearest dollar. You can use the same keys as in profits.
print(fin_summ)
Given a nested list, use a nested loop to print all the items
in the list.
EXERCISE III
list1 =
[[‘Matt’,’Ben’,’Jerry’],[1,2,3,4,5],[‘Denmark’,’England’,’Scotland’]]
Given a nested list, use a nested loop to print all the items
in the list.
list1 =
EXERCISE III
[[‘Matt’,’Ben’,’Jerry’],[1,2,3,4,5],[‘Denmark’,’England’,’Scotland’]]
>>> print(marks)
{'Math':0,'English':0,'Science':0}
Create a dictionary called marks with keys Math, English, Science with a
default value of 0
BONUS CHALLENGE 1
>>> marks={'Math':0,'English':0,'Science':0}
OR
>>> marks
{'Math':0,'English':70,'History':90 }
>>> science_marks
0
1. Add in a new subject History with a score of 90
2. Add in a new subject Geography with a score 60
BONUS CHALLENGE 1
3. Update the English score to be 70
4. Remove the last item of the dictionary
5. Remove Science from the dictionary and assign its value to a variable
called science_marks
>>> marks[‘History’] = 90
>>> marks[‘Geography’] = 60
>>> marks[‘English’] = 70
>>> marks.popitem() OR del marks[‘Geography’]
>>> science_marks = marks.pop(‘Science’)
6. Use a for loop to print the dictionary keys
7. Use a for loop to print the dictionary values
BONUS CHALLENGE 1
8. Use a for loop to print the key value pairs
9. Create a sorted list of the dictionary keys titled subjects
10. Create a sorted list of the dictionary values titled scores
6. Use a for loop to print the dictionary keys
7. Use a for loop to print the dictionary values
BONUS CHALLENGE 1
8. Use a for loop to print the key value pairs
9. Create a sorted list of the dictionary keys titled subjects
10. Create a sorted list of the dictionary values titled scores
Math Math
English English
History History
6. Use a for loop to print the dictionary keys
7. Use a for loop to print the dictionary values
BONUS CHALLENGE 1
8. Use a for loop to print the key value pairs
9. Create a sorted list of the dictionary keys titled subjects
10. Create a sorted list of the dictionary values titled scores
0
70
90
6. Use a for loop to print the dictionary keys
7. Use a for loop to print the dictionary values
BONUS CHALLENGE 1
8. Use a for loop to print the key value pairs
9. Create a sorted list of the dictionary keys titled subjects
10. Create a sorted list of the dictionary values titled scores
('Math', 0)
('English', 70)
('History', 90)
6. Use a for loop to print the dictionary keys
7. Use a for loop to print the dictionary values
BONUS CHALLENGE 1
8. Use a for loop to print the key value pairs
9. Create a sorted list of the dictionary keys titled subjects
10. Create a sorted list of the dictionary values titled scores
>>> scores=sorted(marks.values())
>>> scores
[0, 70, 90]
Create a 2-dimensional array called 2D_array, use a nested for loop to print
out each number in the array on a seperate line
BONUS CHALLENGE 2
1
2
3
4
>>> 2D_array = [[1, 2, 3, 4], [5, 6], [7, 8, 9],[10, 11, 12]] 5
6
7
8
9
Create a 2-dimensional array called 2D_array, use a nested for loop to print
out each number in the array on a seperate line
BONUS CHALLENGE 2
>>> 2D_array = [[1, 2, 3, 4], [5, 6], [7, 8, 9],[10, 11, 12]]
>>> for i in range(len(2D_array)):
for j in range(len(2D_array[i])):
print(2D_array[i][j])
1
2
3
4
5
6
7
8
9