Lecture 5 - Lists
Lecture 5 - Lists
Synopsis
This lecture will walk you through the different data structures used in Python.
You will explore lists, list-of-lists, tuples, sets and some of their associated methods and
functions.
Objectives
After the end of this lecture you will be able to:
Define lists.
Employ list methods and functions.
Construct programs to access whole lists or elements of lists.
Demonstrate the use of the range() function.
Convention(s):
In programs, examples, or statements anything shown in bold font is the component the
user has to type.
Colors and bold fonts in other places are used for reasons of emphasis and/or focus
points.
Labs Note: In the hands-on lab(s) you will be asked to code and run programs based on
materials covered on this, and previous lectures.
Lists
Lists
Lists are ordered (indexed) sequences of arbitrary data that is mutable.
Mutable means that the length of the sequence can be changed and elements can be substituted.
Lists can be of any data, of one type or mixed type, and can be written explicitly.
Creating Lists
The following are examples of how you can create lists.
1. ['red', 'green', 'blue']
This is a list of strings. It is a list because it has elements, enclosed in square
brackets. All the elements are strings and are separated by commas.
2. [1, 3, 5, 7, 9, 20, 69, 11]
This is a list of integers, because all the elements of this list are integers
3. ['silly', 57, 'mixed', -23, 'example']
The elements of this list are mixed data-types, because it contains some elements
that are strings and some that are integers.
4. [ ] This is an empty list- You first create an empty list and later you can populate it.
The following example is a program that assigns a list and then displays each element. The
example has the actual code, comment, and its output.
grades=[67, 85, 89, 34] #list grades has 4 elements
grades[0] 67 grades[-4] 67
grades[1] 85 grades[-3] 85
grades[2] 89 grades[-2] 89
grades[3] 34 grades[-1] 34
From the output you can observe that [0] and [-4] refer to the same element.
To access the entire list all you need to do is use the list’s name.
>>> print(x[-1])
50
When accessing list elements, precautions must be taken so that you do not exceed the list’s
boundaries. An error, out of range, will occur if you do, as shown in the example below.
The following example is a program that that displays an error because the list’s boundaries were
exceeded. The example has the actual code, and its output.
L7E2.py
grades = [67, 85, 89, 34]
print(grades)
print(grades[5])
Instead of using three different statements, you could use one multi-assignment statement. The
following statement has the same effect as the above three.
The following example is a program that uses a list multi-assignment statement. The example
has the actual code, and its output.
L7E3.py
#Version of L7E3.py
The following example is a program that modifies a list’s element. The example has the actual
code, comment, and its output.
L7E4.py
The following examples are 2 programs showing how you can delete an element or a list. The
examples have the actual code, and their output.
Examples 5 and 6
L7E5.py L7E6.py
The following example is a program that shows how to update elements of a list. The example
has the actual code, its output, and comments.
L7E7.py
myList=["Petros", 45] Create myList
print(myList)
objectName.methodName(parameters)
You also know that everything in Python is an object. Therefore lists are also objects, and lists
have associated methods that you can use. The table below shows you the most common
methods associated with lists.
Table of Common List Methods
Assume L is a list
Method description
List3.py Output
print('The new list is:', L) The new list is: [1, 3, 2, 5, 100, 6, 7, 4, 3, 5, 8, 20, 5,
print('The length of the new list is:', len(L)) 50]
print() The length of the new list is: 14
print('Remove the last element.', L.pop())
print(L) Remove the last element. 50
[1, 3, 2, 5, 100, 6, 7, 4, 3, 5, 8, 20, 5]
print('Remove the 5th element.', L.pop(4)) Remove the 5th element. 100
print('Remove the first 5 from list.', L.remove(5))
print(L)
Remove the first 5 from list. None
print() [1, 3, 2, 6, 7, 4, 3, 5, 8, 20, 5]
L.sort()
print('The sorted list is: ', L)
The sorted list is: [1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 20]
info = ["Petros","Passas", "Anna", 'Aris', 'alha']
info.sort()
print(info)
['Anna', 'Aris', 'Passas', 'Petros', 'alha']
L.reverse()
print('The reversed list is:',L)
The reversed list is: [20, 8, 7, 6, 5, 5, 4, 3, 3, 2, 1]
List User Input
You can have the user populate the list. To do so, you must perform the following two steps.
The following example demonstrates the method using while loop. Do not worry if you cannot
understand it at the moment, because loops will be covered in the next lecture.
values =[ ]
num = 1
while num < 5:
price=float(input('Enter a price: '))
values.append(price)
num += 1
print()
print('The values entered are: ',values, end=' ')
Enter 3 integers:10 20 30
Initial list: [ ]
L = list(SetValues)
sort2=sorted(L)
print('Sorted list =',sort2)
Sorted = [1.2, 34.5, 34.5, 100, 207, 300, 301, 567.2, 567.2]
No repeats = {1.2, 34.5, 100, 300, 301, 207, 567.2}
Sorted list = [1.2, 34.5, 100, 207, 300, 301, 567.2]
In addition to methods you can also use some list functions, shown in the table below.
Assume L is a list
enumerate(L) Returns all the values with their corresponding indexes (index, value)
max(L) Returns the list-item with that has the max value
min(L) Returns the list-item with that has the min value
sorted(L) Returns a sorted list, but does not change the original list
The following example is a program that uses list functions. The example has the actual code,
and its output.
List2.py
myList=['Petros', 45]
List=['940 Progress Ave.']
numList=[1,2,3, 4, 5]
The string is converted into a List: ['P', 'e', 't', 'r', 'o', 's']
The length of the list is: 5
The max value in the list is: 30
The min value in the list is: 1
The sorted list is: [1, 2, 6, 15, 30]
The sum of all elements in list is: 54
The range() Function
There is a built-in function range(), that can be used to automatically generate regular arithmetic
sequences.
The range() is useful when you need to generate a list sequence.
The following table shows the ways you can use the range() function.
Function Description
range(n) Where n is the number of elements;
the first element is index 0, and last n-1
range(n, m) start at n and stop at m-1
range(begin, end, step) Begin, increment by step, stop at end-1
The following are examples of statements and their respective output, that use the range()
function to generate lists.
>>> list(range(4)) [0, 1, 2, 3]
[[1, 2, 3, 4, 5], [10, 20, 30, 40, 50], [15, 2, 25, 35, 45]]
Exercises
1. Write the statement to print the 3rd element of a list grades=[67, 85, 89, 34]
1. print(grades[2])