0% found this document useful (0 votes)
59 views16 pages

Lecture 5 - Lists

The document discusses lists in Python. It defines lists and their basic syntax and formatting. It describes how to access elements, modify elements by adding, removing, or updating them. It also discusses various list methods like append, count, index, insert and more.

Uploaded by

godswille2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views16 pages

Lecture 5 - Lists

The document discusses lists in Python. It defines lists and their basic syntax and formatting. It describes how to access elements, modify elements by adding, removing, or updating them. It also discusses various list methods like append, count, index, insert and more.

Uploaded by

godswille2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

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.

The basic format is a square-bracket-enclosed [ ], comma-separated list of arbitrary data.

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.

Accessing List Elements


The list elements are indexed.
For a list of n elements, the first element has an index [0] and the last [n-1].
To access the list elements use the list-name and the element’s index. The index can be positive
or negative.
If you use a negative index, the counting starts from right, where [-1] is referring to the last
element. Therefore, [0] and [-n] refer to the first element.

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

print('grades[0]',grades[0], '\t', 'grades[-4]',grades[-4])


print('grades[1]',grades[1], '\t', 'grades[-3]',grades[-3])
print('grades[2]',grades[2], '\t', 'grades[-2]',grades[-2])
print('grades[3]',grades[3], '\t', 'grades[-1]',grades[-1])

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.

Example accessing the full list


>>> x = [10, 20, 30, 40, 50]
… print(x)

[10, 20, 30, 40, 50]

Example accessing list elements


>>> print(x[0], x[2])
10 30

>>> x[-2] #count from right. Last sub =-1


40

>>> 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])

[67, 85, 89, 34]

Traceback (most recent call last):


File "E:/Cen/Python/P3/general.py", line 4, in <module>
print(grades[5])
IndexError: list index out of range
Multiple Assignment
Suppose you have the following list: info = [‘Petros’, ‘Passas’, ‘123-456-789’]

You could assign variables to each one of the elements like:


fName = info[0]
lName = info[1]
Id = info[2]

Instead of using three different statements, you could use one multi-assignment statement. The
following statement has the same effect as the above three.

fName, lName, Id = info or fName, lName, Id = [‘Petros’, ‘Passas’, ‘123-456-789’]

The following example is a program that uses a list multi-assignment statement. The example
has the actual code, and its output.
L7E3.py

fName, lName, Id =['Petros', 'Passas', '123-456-789']

print('%-20s' %'First Name:', fName, '\n%-20s'%'Last Name:', lName, '\n%-20s'%'Id:', Id)

First Name: Petros


Last Name: Passas
Id: 123-456-789

#Version of L7E3.py

info=['Petros', 'Passas', '123-456-789']

fName, lName, Id = info

print('%-20s'%'First Name:',fName,'\n%-20s'%'Last Name:', lName, '\n%-20s'%'Id:',Id)

fName, lName, Id =['Petros', 'Passas', '123-456-789']

print('%-20s' %'First Name:',fName)


print('%-20s'%'Last Name:',lName)
print('%-20s'%'Id:', Id)

First Name: Petros


Last Name: Passas
Id: 123-456-789
Modifying a List
Lists are mutable and therefore you can overwrite, delete, or add elements.
To overwrite an element all you have to do is to access the element using its index and assign it a
new value.

The following example is a program that modifies a list’s element. The example has the actual
code, comment, and its output.
L7E4.py

grades=[67, 85, 89, 34]


print(grades)
grades[-1]=93 #change the last element form 34 to 93
print(grades)

[67, 85, 89, 34]


[67, 85, 89, 93]

As you can see the last element has been changed to 93

Deleting Element or Whole List


To delete an element use the reserved word del with the associated indexed element, and to
delete a whole list use the reserved word del with the associated name of the list.
Examples: del grades[1], del grades.

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

grades=[67, 85, 89, 34] grades=[67, 85, 89, 34]


print(grades) print(grades)
del grades[1]
print(grades) del grades
print(grades) # grades does no longer exist

[67, 85, 89, 34] [67, 85, 89, 34]


[67, 89, 93]
File "E:/Cen/Python/P3/List2.py", line 5, in
<module>
print(grades)
NameError: name 'grades' is not defined

Process finished with exit code 1


Updating List Objects
You can overwrite single or multiple elements, but you cannot add extra elements unless you use
the append( ), or some other list method as you will see next (List Methods).

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)

myList[0], myList[1] = 'Passas',50 Change first element from ‘Petros’ to ‘Passas’


print(myList) and 45 to 50.
['Petros', 45]
['Passas', 50]
List Methods
Earlier you used methods that were associated with strings, and as you recall the general syntax
of using an object with its associated method was the doted notation:

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

L.append(obj) Appends object obj to L. If obj is a list it will append a list to L

L.count(obj) Returns count of how many times obj occurs in L

L.extend(L2) Appends the contents of list L2 to list L

L.index(obj) Returns the lowest index in L that obj appears

L.insert(index, obj) Inserts object obj into L at offset index

L.pop() Removes and returns last object from L


L.pop(index) Removes and returns indexed object from L

L.remove(obj) Removes first occurrence of object obj from L

L.reverse() Reverses objects of L in place. Original L is modified

L.sort() Sorts objects of L. New L is created with sorted values


The following example is a program that uses list methods. The example has the actual code, and
its output.

List3.py Output

L=[1, 3, 2, 5, 6, 7, 4, 3 ,5, 8, 20, 5]


Info =[‘Petros’, ‘Passas’, ‘Aris’, ‘anna’]

print(L) [1, 3, 2, 5, 6, 7, 4, 3, 5, 8, 20, 5]


print()
print('The length of the list is:', len(L)) The length of the list is: 12

print('Append value 50 to L: ',L.append(50)) Append value 50 to L: None


print('The new list is:', L) The new list is: [1, 3, 2, 5, 6, 7, 4, 3, 5, 8, 20, 5, 50]
print('Find how many times 5 exists in L:',L.count(5)) Find how many times 5 exists in L: 3
print()

print('Find the lowest index of 2 in L : ',L.index(2)) Find the lowest index of 2 in L : 2


print('Insert value 100 to L at index [4]: Insert value 100 to L at index [4]: None
',L.insert(4,100))

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.

1. Create an empty list


2. Use the append() method to append one element at a time or, use a while loop.

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 a price: 1.29


Enter a price: 3.45
Enter a price: 6.88
Enter a price: 9.89

The values entered are: [1.29, 3.45, 6.88, 9.89]


Process finished with exit code 0

Append one element at a time.


myList= []

num1, num2, num3 = map(int, input('Enter 3 integers:'). split())


print('Initial list: ',myList)
print( )
myList.append(num1)
myList.append(num2)
myList.append(num3)
print('Appended list: ', myList)

Enter 3 integers:10 20 30
Initial list: [ ]

Appended list: [10, 20, 30]


Program uses append(), extend(), sorted(), converts list to set to remove repeats
values =[1.2, 567.2, 34.5]

print('Original list =',values)


L.extend(L2): appends
values.extend([207, 567.2, 34.5, 301, 100]) the L2 elms to L
print('Extended list =',values)

values.append(300) L.append(obj): appends


print('Appended list =',values)
print()
a single value to L

sort1=sorted(values) sorted(L): creates new


print('Sorted =',sort1)
list
SetValues=set(sort1)
print('No repeats = ',SetValues)

L = list(SetValues)
sort2=sorted(L)
print('Sorted list =',sort2)

Original list = [1.2, 567.2, 34.5]


Extended list = [1.2, 567.2, 34.5, 207, 567.2, 34.5, 301, 100]
Appended list = [1.2, 567.2, 34.5, 207, 567.2, 34.5, 301, 100, 300]

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]

Appending element or a list to a list.


values =[1.2, 567.2] We can append a
print('Original list =',values) single element, but if
we append a list to a
values.extend([207, 100]) list, the new list is
print('Extended list =',values)
appended as a list.
values.append(300) If we need to append
print('Appending an element to the list =',values)
values.append([400, 500])
the element of the list
print('Appending a list to the list =',values) to another list we need
to use extend().
Original list = [1.2, 567.2]
Extended list = [1.2, 567.2, 207, 100]
Appending an element to the list = [1.2, 567.2, 207, 100, 300]
Appending a list to the list = [1.2, 567.2, 207, 100, 300, [400, 500]] List appended to the
Process finished with exit code 0 list
List Functions

In addition to methods you can also use some list functions, shown in the table below.

Assume L is a list

choice(L) Returns a randomly selected item from the list

enumerate(L) Returns all the values with their corresponding indexes (index, value)

list() Converts any iterable (tuple, string, set) into a list

len(L) Gives the total length of the list

max(L) Returns the list-item with that has the max value

min(L) Returns the list-item with that has the min value

shuffle(L) Shuffles the items in the list

sorted(L) Returns a sorted list, but does not change the original list

sum(L) Returns the sum of all the elements in the 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]

print('The length of myList is: ', len(myList))


print('The list has:',len([1, 2, 9, 11 ,25]), 'elements')

print('This is a concatenated list.', numList + [6,7,8,9])

print('Print 3 times myList: ', myList * 3)

print('3 is a member of numList: ', 3 in numList)

The length of myList is: 2


The list has: 5 elements
This is a concatenated list. [1, 2, 3, 4, 5, 6, 7, 8, 9]
Print 3 times myList: ['Petros', 45, 'Petros', 45, 'Petros', 45]
3 is a member of numList: True
Another example using list functions
List4.py

L1 = [1, 30, 2, 15, 6]


str = 'Petros'

print('The string is converted into a List:', list(str))


print('The length of the list is: ', len(L1))
print('The max value in the list is: ', max(L1))
print('The min value in the list is: ', min(L1))
print('The sorted list is: ', sorted(L1))
print('The sum of all elements in list is:', sum(L1))

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]

>>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list(range(5,16)) [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

>>> list(range(2, 12, 3)) [2, 5, 8, 11]

>>> list(range(2, 12, 2)) [2, 4, 6, 8, 10]


How to populate a list of lists with user input
Problem: 3 team play 5 games. Program to accept and display the points for each team.
team=[]

for i in range (3):


points=[]
for j in range (5):
print("Enter the points of game", j+1, end='')
print(': ', end='')
score= int(input())
points.append(score)
team.append(points)
print()
print(team)

Enter the points of game 1: 1


Enter the points of game 2: 2
Enter the points of game 3: 3
Enter the points of game 4: 4
Enter the points of game 5: 5

Enter the points of game 1: 10


Enter the points of game 2: 20
Enter the points of game 3: 30
Enter the points of game 4: 40
Enter the points of game 5: 50

Enter the points of game 1: 15


Enter the points of game 2: 2
Enter the points of game 3: 25
Enter the points of game 4: 35
Enter the points of game 5: 45

[[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]

2. You have a list player = [‘Leo’, ‘Messi’, ‘goals’, ‘600’]


print the following info as shown below

Player first name: Leo


Player last name: Messi
Goals scored: 600

3. You are given grades=[67, 85, 89, 34]


Write a program that will find and display the average of the marks
Exercise Answers

1. print(grades[2])

2. player = ['Leo', 'Messi', 'goals', '600']

print('%-25s'%'Player first name: ',player[0])


print('%-25s'%'Player last name: ',player[1])
print('%-25s'%'Goals scored: ',player[3])

3. grades=[67, 85, 89, 34]


sum = sum(grades)
elms = len(grades)
avg = sum/elms

print('The average of the grades is: %.2f' %avg )

You might also like