Version 1.0. Prepared by Makzan, 2020 June.
In last lecture, we learn to store values into variables. There were int
, float
, string
, boolean
. They are all singular value. In this notebook, we learn to store a collection of values by using list
, tuple
, dictionary
, and Named Tuple
.
We can create list by using [ ]
brackets. Then we separate each item by comma. For example: the following create a list with 4 items.
[1,2,3,4]
[1, 2, 3, 4]
We need a variable to store the list. Otherwise, we cannot reference the list anymore.
sample_list = [1,2,3,4]
There are basic built-in list functions: len
, max
, min
, sum
.
len(sample_list)
4
max(sample_list)
4
min(sample_list)
1
sum(sample_list)
10
sum(sample_list)/len(sample_list)
2.5
The following example create a list that stores 5 names.
names = ['Thomas', 'Steven', 'Jane', 'Tom', 'Susan']
By using len()
, we know that there are 5 items in the list.
len(names)
5
We can get individual item from the list by using [index]
. The index begins with 0.
0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|
Thomas | Steven | Jane | Tom | Susan |
-5 | -4 | -3 | -2 | -1 |
---|---|---|---|---|
Thomas | Steven | Jane | Tom | Susan |
names[0]
'Thomas'
names[1]
'Steven'
names[-1]
'Susan'
names[-2]
'Tom'
We can append new item to the end of the list.
names.append("John")
names
['Thomas', 'Steven', 'Jane', 'Tom', 'Susan', 'John']
We can also insert item into any position of the list. For example, we can insert item to the beginning by using index 0
.
names.insert(0, "Peter")
names
['Peter', 'Thomas', 'Steven', 'Jane', 'Tom', 'Susan', 'John']
Sometimes, we will need to append multile items at once. We can do so by using extend
function.
names.extend(['Victoria', 'Terence', 'Eric', 'Nicolas', 'Thomas'])
names
['Peter', 'Thomas', 'Steven', 'Jane', 'Tom', 'Susan', 'John', 'Victoria', 'Terence', 'Eric', 'Nicolas', 'Thomas']
If we need to remove an item, we can use remove
and provide the item value.
names.remove('Thomas')
names
['Peter', 'Steven', 'Jane', 'Tom', 'Susan', 'John', 'Victoria', 'Terence', 'Eric', 'Nicolas', 'Thomas']
If we know the index of the item, we can use del
to delete the item by using index. Beware that del
is not a function. There is no ( )
when using del
.
del names[1]
names
['Peter', 'Jane', 'Tom', 'Susan', 'John', 'Victoria', 'Terence', 'Eric', 'Nicolas', 'Thomas']
Assuming now we want to store a list of cities. They are:
'Macao', 'Beijing', 'Helsinki', 'Kyoto', 'Sydney'
# Your code here
cities = None
cities
Expected result |
---|
['Macao', 'Beijing', 'Helsinki', 'Kyoto', 'Sydney'] |
Now we want to append city "Hong Kong" to last of the list. Please use append()
to append the item.
# Your code here
None
cities
Expected result |
---|
['Macao', 'Beijing', 'Helsinki', 'Kyoto', 'Sydney', 'Hong Kong'] |
Now we want to prepend city "Shanghai" to the first of the list. Please use insert()
to prepend the item.
# Your code here
None
cities
Expected result |
---|
['Shanghai', 'Macao', 'Beijing', 'Helsinki', 'Kyoto', 'Sydney', 'Hong Kong'] |
Now we want to append a list of cites to the current cities
list. We can use extend()
to do so. Given the following new_cities
list.
new_cities = ['London', 'Stockholm', 'Sao Paulo']
# Your code here
None
cities
Expected result |
---|
['Shanghai', 'Macao', 'Beijing', 'Helsinki', 'Kyoto', 'Sydney', 'Hong Kong', 'London', 'Stockholm', 'Sao Paulo'] |
Given a list L, we can extract individual item by using L[index]
where index begins with 0. For example, L[0]
to get the first item, L[-1]
to get the last item.
We can also extract a range of items by using slicing. The syntax is [ start : end : step ]
.
The range includes the start
index and exclude the end
index.
sample_list = [1,2,3,4,5,6,7,8,9,10]
sample_list[0:5]
[1, 2, 3, 4, 5]
Item at index 1—3 (index begins with 0)
sample_list[1:4]
[2, 3, 4]
Item at index 1, 3
sample_list[1:4:2]
[2, 4]
We can omit 0 for the starting index. For example, this gets the first 5 items.
sample_list[:5]
[1, 2, 3, 4, 5]
Items from beginning to last 5th item.
sample_list[:-5]
[1, 2, 3, 4, 5]
We need to omit the end value to indicate until-the-end. For example, this gets the last 3 items.
sample_list[-3:]
[8, 9, 10]
Every second item from beginning to end
sample_list[::2]
[1, 3, 5, 7, 9]
A copy of the whole list
sample_list[:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
A copy of the whole list, in reversed order
sample_list[::-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Tuple is the read-only version of list. We can express a tuple by using ( )
.
sample_tuple = (1,2,3,4,5,6,7,8,9,10)
We can read the Tuple as same as reading List. But we cannot modify the Tuple.
sample_tuple[0]
1
Dictionary is a collection of key-value pairs. We can express a dictionary by using { }
with keys and values inside.
It is useful to collect information for the same subject together in one place. For example, we can store a student profile inside a dictionary. The benefit is that we can
sample_dict = {
'name': 'Thomas',
'score': 65
}
sample_dict
{'name': 'Thomas', 'score': 65}
We can store dictionaries inside a list. Indeed, an “item” in collection can be another collection. So we can put dictionary inside list. Or we can put list inside dictionary.
students = [
{'name': 'Thomas', 'score': 65},
{'name': 'Alan', 'score': 95},
{'name': 'Jane', 'score': 85},
{'name': 'Susan', 'score': 75},
{'name': 'Chris', 'score': 45}
]
Here is another example that put a list as value inside dictionary.
student_a = {
'name': 'Steven',
'email': 'steven@example.com',
'classes': [
'Introducing Python',
'Web scraping with BeautifulSoup',
'Plotting graph with MatPlotLib'
]
}
Assuming now we want to store data of book. There are 3 attributes for each book. They are title
, category
, price
.
Please create a book
varibale to store the following book.
title | category | price |
---|---|---|
Python Tricks | Programming | 240 |
book = None
book
Expected result |
---|
{'title': 'Python Tricks', 'category': 'Programming', 'price': 240} |
Now we want to store a list of books. Here is the books data:
title | category | price |
---|---|---|
Python Tricks | Programming | 240 |
Python Crash Course | Programming | 200 |
Getting Real | Startup | 200 |
book_a = None
book_b = None
book_c = None
books = [
book_a,
book_b,
book_c
]
books
[None, None, None]
Expected result |
---|
[ {'title': 'Python Tricks', 'category': 'Programming', 'price': 240}, {'title': 'Python Crash Course', 'category': 'Programming', 'price': 200}, {'title': 'Getting Real', 'category': 'Startup', 'price': 200} ] ||
Assuming now we have a list of numbers
sample_list = [1,2,3,4,5,6,7,8,9,10]
How to get the last item in the list?
sample_list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Expected result |
---|
10 |
How to get last 3 items in the list?
sample_list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Expected result |
---|
[8, 9, 10] |
How to get the first 3 items in the list?
sample_list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Expected result |
---|
[1, 2, 3] |
Now assume we have a list of books.
books = [
{'title': 'Python Tricks', 'category': 'Programming', 'price': 240},
{'title': 'Python Crash Course', 'category': 'Programming', 'price': 200},
{'title': 'Getting Real', 'category': 'Startup', 'price': 200}
]
How to get the first book title?
result_1 = None
result_1
Expected result |
---|
Python Tricks |
How to get the price of last book?
result_2 = None
result_2
Expected result |
---|
200 |
def hello_boss(result_1, result_2):
if result_1 == "Python Tricks" and result_2 == 200:
print("Congratulations! You passed Lesson 2 Collection.")
elif result_1 == "Python Tricks":
print("Sorry! Your result 2 is incorrect.")
elif result_2 == 200:
print("Sorry! Your result 1 is incorrect.")
else:
print("Sorry! Your results are incorrect.")
hello_boss(result_1, result_2)
Sorry! Your results are incorrect.
Expected result |
---|
Congratulations! You passed Lesson 2 Collection. |
In this notebook, we learned the essential techniques to store a series of data into list. Next, we will take a look at logic-flow with if-condition and for-loop.