Uploaded by jlphoenix9

C105 L08 Worksheet-Part1 Python

advertisement
16/06/2020
C105_L08_Worksheet-Part1
C105 Introduction to Programming
Lesson 8 Worksheet
Section A - Python List Fundamentals
RECAP - The 4 main datatypes
We have seeen the following 4 main datatypes in Python so far:
1.
2.
3.
4.
**Integer (int)** - represents whole numbers
**Float (float)** - represents numbers with decimal points
**String (str)** - represents set of characters in between single or double quotes
**Boolean (bool)** - represents one of two values: True, False
When we create a variable to store a value with one of the above datatypes, only one value can be stored
for each variable.
List Datatype
In this lesson, we will introduce the List datatype that we can use to store more than one value with a
variable.
I. Creating a list
1. Creating an empty list:
The syntax of List has an opening bracket “[“ and a closing bracket “]”.
Inside the brackets, it could contain anything.
To create an empty list and assigned it to a variable named myList, the syntax is:
myList = [ ]
cket.
#Starts with an Open Square Bracket, ends with a Closed Square Bra
2. Creating a list with values
To create a list that contains values "Apple", "Orange" and assigned them to a List variable named myFruits,
the syntax is:
myFruits = [
#Starts with
#followed by
#ends with a
"Apple", "Orange" ]
an Open Square Bracket,
the items "Apple", "Orange", and
Closed Square Bracket.
IMPORTANT NOTE The order of the items in the List is preserved.
That is, in the above example, "Apple" will be the first item in the List, while "Orange" will be the last item.
II. Printing a List variable
localhost:8888/nbconvert/html/Dropbox/RP/C105-2021-S1/Problems/L08_List (CA)/C105-L08-Student/C105_L08_Worksheet-Part1.ipynb?downl…
2/9
16/06/2020
C105_L08_Worksheet-Part1
Recall the print() function is used to print a string value.
Similar the printing of integers and floats, to print a variable that is a list datatype, we need to first convert it to
a string.
myFruits = [ "Apple", "Oranges" ]
print("The list is " + str(myFruits))
Exercise 1 - Create and Print a List
Create a shopping list to store the following values in the variable, myShoppingList.
Print the values stored in the variable myShoppingList.
Sugar
Fish
Milk
Salt
</ul> Hint - Remember to differentiate variables and values.
In [ ]:
#
#
#
--------Exercise 1 - Write your answers here.
---------
III. Counting number of items in a List - len() function.
len() is a Python built-in function.
Recall print() and input() are other built-in functions that are frequently used.
The len() function returns the number (integer) of items in an object
When the object is a String, the len() function returns the number of characters in the String.
When the object is a List, the len() functions returns the number of items in the List.
Execute Example 1 to study how the len() function is used.
localhost:8888/nbconvert/html/Dropbox/RP/C105-2021-S1/Problems/L08_List (CA)/C105-L08-Student/C105_L08_Worksheet-Part1.ipynb?downl…
3/9
16/06/2020
C105_L08_Worksheet-Part1
In [ ]:
#
#
#
--------Example 1 - Using the len() function
---------
# Using the len() function to find the number of characters in a String
sentence = input("Enter a sentence: ")
slen = len(sentence)
print("There are " +str(slen) + " characters in the string '" + sentence +"'" )
print() #Printing a line break
print() #Printing a line break
myList = [ "Today", "is", "a", "beautiful", "day" ]
# Using the len() function to find the number of characters in a String
llen = len(myList)
print("There are " +str(llen) + " items in the list: " + str(myList) )
Exercise 2 - Using the len() function
Display the number of items in myShoppingList using the len() function.
In [ ]:
# --------# Exercise 2 - Display the number of items in myShoppingList using the len() function.
# --------myShoppingList = ["Egg", "Chicken", "Mutton", "Bread", "Fish"]
#Write your answer below:
localhost:8888/nbconvert/html/Dropbox/RP/C105-2021-S1/Problems/L08_List (CA)/C105-L08-Student/C105_L08_Worksheet-Part1.ipynb?downl…
4/9
16/06/2020
C105_L08_Worksheet-Part1
IV. Adding Items to a List
There are two (2) ways to add more items to a List.
1. Adding an item to the end of a List
2. Adding an item to a specific position in a List
1. Adding an item to the end of a List
The append(item) method add an item to the end of a List.
You need to call the append() method with one parameter. The parameter contains the item that you want to
add to the end of the List.
Method vs Function
A Python method is like a function, except it is attached to an object. When we call a method on an object, it
may make changes to that object. (Reference: https://data-flair.training/blogs/python-method-and-function/
(https://data-flair.training/blogs/python-method-and-function/))
This means to call a Python method, first you need to identify what is the object.
For example, if the object is a List called IamAList, to add an item (a String "apple") to the of this List, the
code is:
IamAList = [] #Create an empty List
IamAList.append("apple")
Compared with a function, not object is required when calling:
sLen = len(IamAList)
print(sLen)
2. Adding an item to a specific position in a List
The insert(index, item) method add an item, according to the index (an integer) indicated.
Index refers to the position of an item in a List.
Index always starts from left with 0 and followed by 1,2,3,4, …
Based on the example above, the item with index 0 is "Egg" (the first item in the List).
And, it is possible to store duplicate items in a List (e.g. "Fish" appears twice in myShoppingList).
To add an item "Milk" as the third item (index is 2) in myShoppingList, the code is:
myShoppingList = ["Egg", "Fish", "Chicken", "Mutton", "Bread", "Fish"]
myShoppingList.insert(2, "Milk") ## Adding the item "Milk" as the 3rd item (inde
x 2) in the List.
localhost:8888/nbconvert/html/Dropbox/RP/C105-2021-S1/Problems/L08_List (CA)/C105-L08-Student/C105_L08_Worksheet-Part1.ipynb?downl…
5/9
16/06/2020
C105_L08_Worksheet-Part1
Exercise 3 - Append method
Create a List called myShoppingList with the following items
Sugar
Fish
Milk
Salt
</ul> Add an item called "Apples" to the end of the List.
In [ ]:
#
#
#
--------Exercise 3 - Write your answers here.
---------
Exercise 4 - Insert method
Add an item called "Chicken" as the fourth item in myShoppingList from Exercise 3.
In [ ]:
#
#
#
--------Exercise 4 - Write your answers here.
---------
localhost:8888/nbconvert/html/Dropbox/RP/C105-2021-S1/Problems/L08_List (CA)/C105-L08-Student/C105_L08_Worksheet-Part1.ipynb?downl…
6/9
16/06/2020
C105_L08_Worksheet-Part1
V. Accessing items in a list
We could access an item in a list by specifying the index of the item in the list.
myShoppingList = ["Egg", "Chicken", "Mutton", "Bread", "Fish"]
1. Display an item in a specified index
To display the fourth item (index: 3) in the above myShoppingList, the code is:
item = myShoppingList[ 3 ] #Use square bracket to indicate the index
print("The fourth item is " + item)
The expected output is:"The fourth item is Bread"
2. Update an item in a specified index
To update the fourth item (index: 3) in the above myShoppingList to "Coconut", the code is:
myShoppingList[ 3 ] = "Coconut" #Use square bracket to indicate the index
print("The fourth item is " + item)
Accessing the last item in a List
To access the last item in a List,
First, we can use the len() function to count the number of items in the List
Next, minus 1 (one) from the count. For example:
myShoppingList = ["Egg", "Chicken", "Mutton", "Bread", "Fish"]
num_item = len(myShoppingList)
last_item = myShoppingList[ num_item - 1 ]
print("The last item is " + last_item)
The expected output is:"The last item is Fish"
Exercise 5 - Update an item in List
Change the last item in myShoppingList to "Kiwi".
In [ ]:
# --------# Exercise 5 - Change the last item in myShoppingList to "Kiwi".
# --------myShoppingList = ["Egg", "Chicken", "Mutton", "Bread", "Fish"]
#Write your answer below:
localhost:8888/nbconvert/html/Dropbox/RP/C105-2021-S1/Problems/L08_List (CA)/C105-L08-Student/C105_L08_Worksheet-Part1.ipynb?downl…
7/9
16/06/2020
C105_L08_Worksheet-Part1
VI. Removing Items from a List
There are multiple ways to remove items from a List.
In today's lesson, we focus on the two following ways:
1. Removing an item by its value
2. Removing an item by its index and getting it value before removing
1. Removing an item by its value
The remove(value) method remove the first item with the specified value from the List.
An example:
myShoppingList = ["Egg", "Fish", "Chicken", "Mutton", "Bread", "Fish"]
myShoppingList.remove("Fish")
The updated myShoppingList is (the first instance of "Fish" is removed):
Exercise 6 - Removing an item by value that is not found in the List
What happens if the value that you want to remove is not found in the List?
Execute the codes in Exercise 6 and write down your observations.
In [ ]:
# --------# Exercise 6 - Execute the codes
# --------myShoppingList = ["Egg", "Chicken", "Mutton", "Bread", "Fish"]
myShoppingList.remove("Milk")
## Write your observations here
localhost:8888/nbconvert/html/Dropbox/RP/C105-2021-S1/Problems/L08_List (CA)/C105-L08-Student/C105_L08_Worksheet-Part1.ipynb?downl…
8/9
16/06/2020
C105_L08_Worksheet-Part1
2. Removing an item by its index and getting its value before removing
The pop(index) method remove the item that is in the index specified from the List.
The value of this item is returned by the pop method.
An example:
myShoppingList = ["Egg", "Chicken", "Mutton", "Bread", "Fish"]
item = myShoppingList.pop(2)
print("The item removed is " + item )
The expected output is: "The item removed is Mutton"
The pop( ) method can also be used without specifying the index.
In this case, the last item is removed by default
An example:
myShoppingList = ["Egg", "Chicken", "Mutton", "Bread", "Fish"]
item = myShoppingList.pop()
print("The item removed is " + item )
The expected output is: "The item removed is Bread"
Exercise 7 - Removing an item by index that is not found in the List
Execute the codes in Exercise 7 and write down your observations.
In [ ]:
# --------# Exercise 7 - Execute the codes
# --------myShoppingList = ["Egg", "Chicken", "Mutton", "Bread", "Fish"]
item = myShoppingList.pop(5)
print("The item removed is " + item )
## Write your observations here
localhost:8888/nbconvert/html/Dropbox/RP/C105-2021-S1/Problems/L08_List (CA)/C105-L08-Student/C105_L08_Worksheet-Part1.ipynb?downl…
9/9
Download