You are on page 1of 42

TECH1200

Fundamentals of
Programming
Lesson 3
Lists
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969

WARNING

This material has been reproduced and communicated to you by or on behalf of


Kaplan Business School pursuant to Part VB of the Copyright Act 1968 (the Act).

The material in this communication may be subject to copyright under the Act. Any
further reproduction or communication of this material by you may be the subject of
copyright protection under the Act.

Do not remove this notice.


Subject Learning Outcomes
1 Interpret simple program
specifications.
2 Produce a high-level model via the use of
pseudocode and flow charts.
3 Transfer a high-level model into a
software application via the use of a
programming language.
4 Use an integrated development
environment to develop, debug and
test a solution written in a
programming language.
5 Use a programming language to read and
write data to a persistent storage.
Lists
• A list is used to store collection of items in
a single variable
• In Python, a list is one of the built-in data
structure or Python collection
• The other 3 Python collections (1) Tuple;
(2) Set; (3) Dictionary. All with different
properties and usage
List
• A list is created using square brackets []
• Each item is separated by a comma ,
– Good Python practice: insert a space after
each comma
• Suppose in this workshop we had four
students. And, their grades were 35, 50,
65, 85. Creating a list of grades can be
done as follows: grades = [35, 50, 65, 85]
What can a List store?
• Simple answer. Anything! Any data type in
Python.
• Lists can even store a combination of
different data types. Notice, there is a list
within a list:
list = ["String", 27, False, 25.65, [1, 2, 3, 4, "Count"], None]

• A list can be empty, and can be created as


follows: list_empty = []
• It can be also created using the list()
Constructor as follows (note the double round
brackets): list_empty = list(())
Activity
Why do you think it may be useful to have an
empty list? Can you imagine a scenario where
it could be useful?

Answer:
It may be useful to have an empty list because
we intend to use it later in the code based on
specific conditions. One scenario (and there
are many) could be asking users to provide
number guesses, and doing some form of
analysis.
List Methods
• In Python, for any built-in data type
(Strings, Boolean, Lists, and so on), there
are built-in functionality that can be used
to achieve specific tasks
• For lists, methods need to adhere to the
following form:
# list_name is our list
# .method() is a method of our list
# This example is for structure illustration,
# it will not work
list_name.method()
List Methods (2)
• In the previous slide, if you attempted to
use list_name.method(), Python would
have returned (assuming list_name was
initialised empty at least)
AttributeError: 'list' object has no attribute 'method'

• It states that the method does not exist for


the list object.
Check Methods - Documentation
• Use the following official website:
1. Official Python Docs:
https://docs.python.org/3/tutorial/datastructures.html
• Use any other unofficial websites:
2. W3Schools Docs:
https://www.w3schools.com/python/python_ref_list.a
sp
3. GeeksforGeeks Docs:
https://www.geeksforgeeks.org/list-methods-in-
python/
• These websites are not limited just for lists.
There are other fantastic resources which will be
useful in your journey for this subject!
List Method: .append()
• The list method .append() adds an
element to the end of a list
• Example below, the append method is
used to add a fifth student grade to an
existing grades list, with a value or grade
of 67:
grades = [35, 50, 65, 85]
grades.append(67)
print(grades) # Prints [35, 50, 65, 85, 67]
Adding multiple items to a list
• append method appends a single value
• To append multiple values, use either
extend method or plus sign +
• Example below, five more student grade
values are added. Three with plus sign,
and two with extend method:
grades = [35, 50, 65, 85, 67]
grades += [76, 78, 52] # OR grades = grades + [76, 78, 52]
grades.extend([68, 72]) # square brackets are used here and above
print(grades) # prints [35, 50, 65, 85, 67, 76, 78, 52, 68, 72]
Accessing list elements
• Use the students list, to call each student to present:
students = ['Jing', 'Jim', 'Kerrie', 'Rakesh']
• In Python, the location of an element in a list is its index
• Python lists are zero indexed. Put simply, the first
element in a list has an index of 0, as opposed to 1
• The index numbers for the students list:
Element Index
‘Jing’ 0
‘Jim’ 1
‘Kerrie’ 2
‘Rakesh’ 3
Accessing list elements (2)
students = ['Jing', 'Jim', 'Kerrie', 'Rakesh']

Element Index
‘Jing’ 0
‘Jim’ 1
‘Kerrie’ 2
‘Rakesh’ 3
• The element with index 1 is ‘Jim’
– We can access this element from a list using square brackets:
students = ['Jing', 'Jim', 'Kerrie', 'Rakesh']
print(students[1]) # prints Jim
• Note, an int type must be used to access the list element
Accessing list elements (3)
students = ['Jing', 'Jim', 'Kerrie', 'Rakesh']

Element Index Negative


Index
‘Jing’ 0 -4
‘Jim’ 1 -3
‘Kerrie’ 2 -2
‘Rakesh’ 3 -1

• Negative index can be used to access last element(s) of a list. Very


useful when the list contains a number of elements or/and when the
number of elements in the list is unknown
• The element with a negative index -1 is ‘Rakesh’
students = ['Jing', 'Jim', 'Kerrie', 'Rakesh']
print(students[-1]) # prints Rakesh
Activity
In the previous slide, the following statement was
made: “Very useful when the list contains a number
of elements or/and when the number of elements
in the list is unknown”
• Find if Python has a function* (notice the method
word is not used) that returns the number of things
in a object?
Answer:
It does. One common way is to use len() function.
See W3Schools Docs for more information:
https://www.w3schools.com/python/ref_func_len.asp
Length
• The built-in Python len() function returns
the number of items* in a object*
• When the object is a List, it will return the
number of elements:
students = ['Jing', 'Jim', 'Kerrie', 'Rakesh']
print(len(students)) # prints 4

• When the object is a String, it will return


the number of characters in the string:
guess = 'Howmansafayhschatersarehere can you guess? :-)'
print(len(guess)) # prints 46
Modifying list elements
• Unfortunately, one of the academics gave
a student a grade of 48, instead of a grade
of 50. Lucky for this academic, they know
how to modify their lists…
• The student in question is at index 1 (or
negative index -3). Assign a new value of
50, to the the grades list at index 1:
grades = [35, 48, 65, 85]
grades[1] = 50
print(grades) # prints [35, 50, 65, 85]
Remove list elements
• The same academic was tasked to figure out
how many students passed the subject. They
attempted to remove all element(s) whose
grade value was below 50.
– Lucky for them, there was only one student in the
grades list…
• Three common ways:
1. grades.remove(value)
2. grades.pop(specific_index)
3. del grades[specific_index]
Remove list elements (2)
• Three common ways:
1. grades.remove(value)
grades = [35, 50, 65, 85]
grades.remove(35)
print(grades) # prints [50, 65, 85]

2. grades.pop(specific_index)
grades = [35, 50, 65, 85]
grades.pop(0)
print(grades) # prints [50, 65, 85]

3. del grades[specific_index]
grades = [35, 50, 65, 85]
del grades[0]
print(grades) # prints [50, 65, 85]
Remove list elements (3)
• Additional useful information:
1. grades.remove(value)
a) Uses a value to access an element (instead of index)
b) Removes the first instance of matching element (if there were
multiple 35s, it only removes the first one that matched)
2. grades.pop(specific_index)
a) Uses an index to access an element
b) If specific_index is not provided, it will remove the last
element in the list, when grades.pop() is called
3. del grades[specific_index]
a) Uses an index to access an element
b) del is a keyword to delete objects, as opposed to a specific
List method in (1) and (2) above
• Once an element is removed, the index order of
elements in a list has most likely changed as well
Two Dimensional (2D) Lists
• Recall, that a list can store any type of
data, including a list within a list
– Known as a nested list – this logic can be
applied to create a three dimensional (3D) list
• Recall, from the previous slides in this
workshop that grades and students lists
were used independent of each other
– This did not make sense, as we didn’t know
which student had what grade, we could only
assume that the list order was correct
Two Dimensional (2D) Lists (2)
• Let’s create a new list gradebook that will store
our students and grades lists together:
gradebook = [['Jing', 35], ['Jim', 50], ['Kerrie', 65], ['Rakesh', 85]]

• Or, it can be structured, in a more ‘human-


friendly’ readable version:
gradebook = [
['Jing', 35],
['Jim', 50],
['Kerrie', 65],
['Rakesh', 85]
]
Accessing 2D Lists
• 2D lists can be accessed in a similar
manner as one dimensional lists
– Instead of just providing a single pair of
brackets, 2D lists can use a single pair of
brackets or a double pair of brackets
• For example: gradebook = [
1. Access gradebook index 1: ['Jing', 35],
['Jim', 50],
print(gradebook[1]) # prints ['Jim', 50] ['Kerrie', 65],
['Rakesh', 85]
2. Access Rakesh’s grade value: ]
print(gradebook[-1][1]) # prints 85
Accessing 2D Lists (2)
Element Index Negative Index
['Jing', 35] gradebook[0] gradebook[-4]
['Jim', 50] gradebook[1] gradebook[-3]
['Kerrie', 65] gradebook[2] gradebook[-2]
['Rakesh', 85] gradebook[3] gradebook[-1]
‘Jing’ gradebook[0][0] gradebook[-4][0] OR gradebook[-4][-2]
35 gradebook[0][1] gradebook[-4][1] OR gradebook[-4][-1]
‘Jim’ gradebook[1][0] gradebook[-3][0] OR gradebook[-3][-2]
50 gradebook[1][1] gradebook[-3][1] OR gradebook[-3][-1]
‘Kerrie’ gradebook[2][0] gradebook[-2][0] OR gradebook[-2][-2]
65 gradebook[2][1] gradebook[-2][1] OR gradebook[-2][-1]
‘Rakesh’ gradebook[3][0] gradebook[-1][0] OR gradebook[-1][-2]
85 gradebook[3][1] gradebook[-1][1] OR gradebook[-1][-1]
Activity
• Using the previous slides, an academic
marked Jing’s final assessment and wants to
change Jing’s grade from 35 to 56.
Recommend to the academic how they can
change Jing’s grade in the gradebook list?
• Bonus: how many different ways can you
change it?
Answer: gradebook[0][1] = 56
gradebook[-4][1] = 56
Any one of the three ways: gradebook[-4][-1] = 56
Zip
• The built-in Python zip() function joins lists
together. Extremely powerful!
– Specifically, it returns a zip object – an iterator
of tuples – where the first element in each
passed iterator is paired together, and then
the second element, and so forth.
• If zip parameters – or iterators – lengths are
different, than the iterator with the least element
determines the length of the new iterator
Zip (2)
Using the students and grades lists, the zip function can be
used to pair together:
students = ['Jing', 'Jim', 'Kerrie', 'Rakesh']
grades = [35, 50, 65, 85]
gradebook_zip = list(zip(students, grades))
# print(gradebook_zip) # zip creation - note the tuples
# [('Jing', 35), ('Jim', 50), ('Kerrie', 65), ('Rakesh', 85)]
# print(gradebook) # original
# [['Jing', 35], ['Jim', 50], ['Kerrie', 65], ['Rakesh', 85]]

Note:
• list() constructor must be used to convert zip type to list
type
• Each pair within the gradebook_zip list has a tuple type, as
opposed to a list type (in the original gradebook list)
Tuples
• Tuples do the same operation as Lists.
– However, instead declaring using square brackets
[] like Lists, it uses round brackets ()
tuple_students = ('Jing', 'Jim', 'Kerrie', 'Rakesh')

• A major difference between Lists and Tuples,


is that Tuples are unchangeable
– In other words, once the tuple_students tuple
has been set, then we can’t change, add, or
remove items
– Attempt to alter the tuple and see what happens.
Other useful List Methods
1. .count(): returns the number of times
the specified element appears in the list
2. .insert(): inserts the specified value at
the specified position
3. .sort(): sorts the list ascending by
default
4. .sorted(): returns a sorted list of the
specified iterable object
Recall method versus functions
• Method (using List method example):
# Syntax for List methods
list.method(parameter)

• Built-in function:
# Syntax for a built-in function
builtinfuncion(parameter)

• Recall that we explored the built-in Python


len() length function and zip() zip function.
Another powerful built-in Python function is
the range() range function.
Range
• If you were asked to create a list containing
the numbers 0 through 5, you may do it
manually: numbers = [0, 1, 2, 3, 4, 5]
• If the above task was repeated, creating a list
containing the numbers 0 through 999, would
you still do it manually…?
– (I hope not…)
• This is where range() function can be useful
– It returns a sequence of numbers – starting from
0 by default – and increments by 1 by default,
and stops before a specified number
Range (2)
• In the previous two examples: (1) 0 to 5; and (2) 0 to
999, the range function achieves the same desired
outcome:
– range(6)
– range(1000)
• However, the range() function has a type of <class
‘range’>
– For example try: type(range(6))
• To convert a range type to a list type, we can use the
list() function, which takes a single parameter, to convert
the object to a list type: small = list(range(6))
large = list(range(1000))
Activity
Explore the range() function further. Use Python
Docs, like W3Schools:
https://www.w3schools.com/python/ref_func_range.a
sp. How can we create an even sequence of
numbers ranging from -255 to 255? Make sure it’s in
list format (as opposed to range type)

Answer: ans = list(range(-254, 256, 2))


Somewhat of a cheat/hack solution. We can ignore
negative -255, and start the sequence with an even
number -254. Note that the end sequence must be
256, so that positive 254 is included as well.
Slicing Lists
• Another List manipulation technique is to
extract only a portion of a list, which is
referred to as slicing
• Use the nums list: nums = [0, 1, 2, 3, 4, 5, 6, 7, 8]
– And return only the numbers from 2 to 6:
nums[2:7]
– nums[start:end]
• The start index is 2
• The end index is 7 because the end index is one more
than the last index that we wish to include
• Same slicing logic can be applied to Strings
Slicing Lists (2)
• Splicing just the first three numbers in the
nums list: nums = [0, 1, 2, 3, 4, 5, 6, 7, 8]
• Is achieved by: nums[:3]
• nums[:n]
– The start index is not specified, and by default
will start at first element in the list
– The end index specifies n as the first three
numbers (and does not include the end
number)
Activity
What does the following code do nums[-6:]
when applied to the following nums list:
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8]

Answer:
Output is: [3, 4, 5, 6, 7, 8]
Because the start index (specifically, negative
index) is -6. It starts at negative index -6
(specifically at number 3), and continues until
the end (specifically at number 8).
Sets
• Just like Lists and Tuples, Sets are used to store
collection of items
– Sets are declared using curly brackets {}
• Important Set considerations:
1. Set items are unchangeable
a) The exception: add and remove items allowed
2. Set items are unordered – items can’t be indexed as there’s
no structure
3. And, the most important use of Sets, it can’t have two items
with the same values. Duplicates are not allowed
a) Lists and Tuples allow for duplicates

# prints {65, 50, 35, 85}


grades_set = {35, 50, 65, 85, 85, 85}
print(grades_set)
Dictionary
• Just like Lists, Tuples, and Sets, Dictionaries are
used to store collection of items
– Dictionaries are declared using curly brackets {}, but
store data values in key:value pairs
• Important Dictionary considerations:
1. Duplicates are not allowed – specifically,
dictionaries can’t have two items with the same key.
But, two different keys, can have the same value
2. Changeable – no restrictions, same as Lists
3. Ordered*** - assumes using Python version 3.7. It
is not ordered in Python version 3.6 and earlier. In
this subject, Python version 3.7 and above should
be used
Dictionary (2)
• Creating a gradebook_dict dictionary
with the same student and grade data
values: gradebook_dict = {
'Jing': 35,
'Jim': 50,
'Kerrie': 65,
'Rakesh': 85
}

• Dictionaries can be powerful. Imagine


replacing the value 35, and to have more
data for each student. See next slide.
Dictionary (3)
gradebook_dict = {
'Jing': {
• The ‘Jing’ key had the 'address': 'Fake Rd',
value of 35 updated to 'student_id': 12345,
'ass1_grade': 20,
a dictionary that 'ass2_grade': 15,
'ass3_grade': 0,
contains 6 additional 'final_grade': 35
},
key:value pairs 'Jim': 50,
'Kerrie': 65,
• To access the value 'Rakesh': 85
}
from the ‘Jing’ key:
# prints {'address': 'Fake Rd', 'student_id':
12345, 'ass1_grade': 20, 'ass2_grade': 15,
'ass3_grade': 0, 'final_grade': 35}
print(gradebook_dict['Jing'])
Summary of Python collections
1. List: “is a collection which is ordered and changeable.
Allows duplicate members.”
2. Tuple: “is a collection which is ordered and unchangeable.
Allows duplicate members.”
3. Set: “is a collection which is unordered, unchangeable*, and
unindexed. No duplicate members.”
4. Dictionary: “is a collection which is ordered** and
changeable. No duplicate members.”

*Set items are unchangeable, but you can remove and/or add
items whenever you like.
**As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered.

Source:
https://www.w3schools.com/python/python_dictionaries.asp

You might also like