0% found this document useful (0 votes)
2 views67 pages

08 - Lists

The document provides an overview of lists in Python, detailing their characteristics, such as being mutable and capable of storing different data types. It explains various operations on lists, including indexing, iterating, appending items, and copying lists, along with examples and code snippets. Additionally, it covers methods for searching items, slicing lists, and creating lists from strings or ranges.

Uploaded by

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

08 - Lists

The document provides an overview of lists in Python, detailing their characteristics, such as being mutable and capable of storing different data types. It explains various operations on lists, including indexing, iterating, appending items, and copying lists, along with examples and code snippets. Additionally, it covers methods for searching items, slicing lists, and creating lists from strings or ranges.

Uploaded by

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

08 – Lists

COMP 125 – Programming with Python


Recording Disclaimer

The synchronous sessions are recorded (audiovisual recordings). The students are not required to keep their
cameras on during class.

The audiovisual recordings, presentations, readings and any other works offered as the course materials aim
to support remote and online learning. They are only for the personal use of the students. Further use of
course materials other than the personal and educational purposes as defined in this disclaimer, such as
making copies, reproductions, replications, submission and sharing on different platforms including the digital
ones or commercial usages are strictly prohibited and illegal.

The persons violating the above-mentioned prohibitions can be subject to the administrative, civil, and
criminal sanctions under the Law on Higher Education Nr. 2547, the By-Law on Disciplinary Matters of Higher
Education Students, the Law on Intellectual Property Nr. 5846, the Criminal Law Nr. 5237, the Law on
Obligations Nr. 6098, and any other relevant legislation.

The academic expressions, views, and discussions in the course materials including the audio-visual
recordings fall within the scope of the freedom of science and art.

COMP 125 Programming with Python 2


How can we store and organize data?

§ Collection: A data structure used to store multiple values in a single unit


§ In most other programming languages, the most basic collection is an array,
which stores values of the same type

§ In Python, the most basic, and arguably one of the most useful, collection is
the List data structure

§ List is also a sequence (recall the range function and strings)


§ Elements in a list are ordered

COMP 125 Programming with Python 3


Sequences

§ Sequence: an object that contains multiple items of data


§ The items are stored (ordered) one after another

§ Python provides different types of sequences, including strings, lists and


tuples
§ The difference between these is that a list is mutable, a tuple or string is
immutable

COMP 125 Programming with Python 4


Lists

§ A data type for storing values in a linear collection


§ Python declaration:

§ Write items of the list inside brackets [ ]


§ List items are separated with commas
§ The length of a list is the number of items it contains (just like
strings)
§ Python function len() to return the length of any sequence, also
including a list

COMP 125 Programming with Python 5


Lists

§ Can be defined to keep items of different types

§ Can have a varying number of items including 0 (empty list) and 1

§ Can include items of different data types

COMP 125 Programming with Python 6


String indexing (revisited)

§ Each character in the string is associated with an index


§ index: An integer representing the location of a character in a string
§ Zero-based indexing
§ Indices start with 0 (not 1)
§ The first character of a string exists at index: 0
§ The last character of a string exists at index: len(s)–1
§ Index values >= len(s) are NOT valid
§ Negative indexing
§ Indices may also be negative numbers, to start counting from the rightmost character
§ The last character of a string exists at index: -1
§ The first character of a string exists at index: -len(s)–1
§ Index values <= -len(s)-1 are not valid

H e l l o !
Zero-based indexing
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1 Negative indexing
COMP 125 Programming with Python 7
List indexing

§ Indexing lists is like indexing strings

§ You MUST use valid index values

§ The index of last item is len(list)-1

COMP 125 Programming with Python 8


Iterating over a list

§ Write a code fragment that calculates the sum of the items in a given list

COMP 125 Programming with Python 9


Iterating over a list (using indices)

§ Write a code fragment that calculates the sum of the items in a given list

§ Use the len() function to prevent IndexError when iterating over a list with
a loop

COMP 125 Programming with Python 10


Displaying lists

COMP 125 Programming with Python 11


How to display list items one by one?

Alternative implementation

COMP 125 Programming with Python 12


Lists are mutable

§ Items in a mutable sequence can be modified after the sequence is created


§ Recall: strings are immutable
§ Lists are mutable, and so their items can be modified through indexing

COMP 125 Programming with Python 13


Example

§ Assume that you are given a list consisting of elements of different data
types (int, float, string, etc.)
§ Write a program which replaces elements of string data type with integer -1

COMP 125 Programming with Python 14


Adding an item to a list – append()
§ The append() function adds a single item to the end of a list

COMP 125 Programming with Python 15


Example

§ Write a program that takes student grades from a user, keeps these grades
in a list, and calculates the average grade. The program should continue
taking grades until the user enters a negative value.

COMP 125 Programming with Python 16


Exercise
§ Proteins are composed of 20 different types of
amino acids.
§ The sequence of a protein can be shown by
using the single letter representation for each
amino acid. (e.g. Glycine: G)

§ Ubiquitin amino acid sequence:


“MQIFVKTLTGKTITLEVEPSDTIENVKAKIQDKE
GIPPDQQRLIFAGKQLEDGRTLSDYNIQKESTLH
LVLRLRGG”
Implement a function (analyze_sequence) that
returns a string for unique amino acids and a list
for their frequencies.

COMP 125 Programming with Python 17


Solution
def analyze_protein(protein):
#store the unique residues in a string
unique_res = ''
for residue in protein:
if not residue in unique_res:
unique_res += residue

#create a list same length as 'unique_res'


freq = []
for res in unique_res:
freq.append(0)

for i in range(len(unique_res)):
for j in range(len(protein)):
if protein[j] == unique_res[i]:
freq[i] += 1

return unique_res, freq

def main():
ubi="""MQIFVKTLTGKTITLEVEPSDTIENVKAKIQD\
KEGIPPDQQRLIFAGKQLEDGRTLSDYNIQKESTLHLVLRLRGG"""
unique_res, freq = analyze_protein(ubi)
print(unique_res)
print(freq)

main()
COMP 125 Programming with Python 18
Removing an item of a list by index – pop()
§ The pop(index=-1) function removes the last item in a list and returns
this removed item
§ You can also specify an index

COMP 125 Programming with Python 19


Concatenating lists

§ Concatenate: Join two things together (you have seen the string version)

§ The + operator can be used to concatenate two lists


§ Cannot concatenate a list with another data type, such as a number

§ The += augmented assignment operator can also be used to concatenate


lists

COMP 125 Programming with Python 20


Concatenating lists

You can use += only for concatenating lists!

COMP 125 Programming with Python 21


Copying lists
§ In Python, assigning one variable to another simply makes both variables
reference the same object in memory

We didn’t actually create a


separate copy of the
original list!

COMP 125 Programming with Python 22


Copying lists

§ You may use one of the following to list1 = [1, 2, 3, 4]


create a separate copy of a list list2 = list1.copy()
1. Create a copy of the list using
list.copy() method list2[0] = 99
print(list1)
print(list2)

Output
[1, 2, 3, 4]
[99, 2, 3, 4]

COMP 125 Programming with Python 23


Copying lists

§ You may use one of the following to list1 = [1, 2, 3, 4]


create a separate copy of a list list2 = []
for i in list1:
1. Create a copy of the list using
list2.append(i)
list.copy() method
2. Create a new empty list and add a list2[0] = 99
copy of each item in the original list print(list1)
to the new list print(list2)

Output
[1, 2, 3, 4]
[99, 2, 3, 4]

COMP 125 Programming with Python 24


Copying lists

§ You may use one of the following to list1 = [1, 2, 3, 4]


create a separate copy of a list list2 = []
1. Create a copy of the list using list2 += list1
list.copy() method
2. Create a new empty list and add a list2[0] = 99
copy of each item in the original list print(list1)
to the new list print(list2)
3. Create a new empty list and
concatenate the original list to the Output
new empty list [1, 2, 3, 4]
[99, 2, 3, 4]

COMP 125 Programming with Python 25


Slicing lists
§ Slice: a span of items that are taken from a sequence
§ List slicing format
list[start:end:step]
§ Result is a list containing copies of items from start up to, but not including, end
§ Negative start and end values can be given, which are interpreted relative to the end of the list
§ Slicing expressions can include a non-zero step value (default is 1)
§ If start is not specified default behavior is based on the values below:
§ if step > 0, start = 0
§ if step < 0, start = len(list)
§ If end is not specified default behavior is based on the values below:
§ if step > 0, end = len(list)

§ if step < 0, end = -len(list)-1

COMP 125 Programming with Python 26


Slicing lists

my_list = [44, 55, 66, 77, 88]

my_list[2:4] [66, 77]


my_list[1:] [55, 66, 77, 88]
my_list[:2] [44, 55]
my_list[1:4:2] [55, 77]
my_list[1:3:2] [55]
my_list[3:1] []
my_list[3:1:-1] [77, 66]

COMP 125 Programming with Python 27


Slicing lists

my_list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

list1[::-1] ['e', 'd', 'c', 'b', 'a']

list1[::2] ['a', 'c', 'e']

list1[::-2] ['e', 'c', 'a']

COMP 125 Programming with Python 28


Copying lists (yet another method)

You may use slicing to create a list1 = [1, 2, 3, 4]


separate copy of a list list2 = list1[:]

list2[0] = 99
print(list1)
print(list2)

Output
[1, 2, 3, 4]
[99, 2, 3, 4]

COMP 125 Programming with Python 29


Passing/returning lists to/from functions

§ Remember: if you change the value of a parameter in a function, you


cannot see this change after this function returns
§ However, if you change the value of a list item, you will see this
change after the function returns

COMP 125 Programming with Python 30


Passing/returning lists to/from functions

§ To preserve the original list, you can use the slicing operation

COMP 125 Programming with Python 31


Example

§ Write a function that continuously takes students’ grades as input from the
console, stores them in a list, and returns the list at the end. A grade is valid
only if it is between 0 and 100. The function continues taking the grades
until an invalid grade is entered.

COMP 125 Programming with Python 32


Example

§ Write another function that takes a list containing students’ grades as input,
computes the average grade, and returns it.

COMP 125 Programming with Python 33


Example

§ Write a main function that calls these two functions to:


§ First get the students’ grades from the user
§ Then display the average on the screen

COMP 125 Programming with Python 34


Example

§ Write a function that takes a list as its parameter and returns two lists
containing odd and even items in the input list. You may assume that all list
items are integers.

COMP 125 Programming with Python 35


Solution

COMP 125 Programming with Python 36


Searching for an item in a list

§ The in operator can be used to determine whether an item is in the list


§ It returns True if the item is in the list, False otherwise
§ The not in operator can be used to determine whether an item is not in
the list

COMP 125 Programming with Python 37


Example: Searching for an item in a list

§ Now let’s write our own search function. This function takes a list and an
item value as its parameters and returns the index of this item if it is found
in the list. Otherwise, if the item is not in the list, it returns -1. You may
assume that the list contains unique item values.

COMP 125 Programming with Python 38


Solution

COMP 125 Programming with Python 39


More on Lists
Repetition operator

§ The * operator makes multiple copies of a list and joins them all together

COMP 125 Programming with Python 41


Splitting strings to make a list

§ The split() function splits a string where there is a white space

COMP 125 Programming with Python 42


Splitting strings to make a list

§ split(delimiter) splits a string where there is the delimiter

COMP 125 Programming with Python 43


Splitting strings to make a list

COMP 125 Programming with Python 44


Creating a list from the range function

§ Recall the range function that creates an implicit sequence

numbers = list (range(5))


[0, 1, 2, 3, 4]

numbers = list (range(0, 10, 2)) Type Conversion!


[0, 2, 4, 6, 8]

numbers = list (range(10, -1, -1))


[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

COMP 125 Programming with Python 45


Useful list methods

Function Description
copy() Return a shallow copy of the list.
append(object) Append object to the end of the list.
insert(index, object) Insert object before index.
When an item is inserted into a list, the list is expanded in size to accommodate the
new item. The item that was previously at the specified index, and all the items after
it, are shifted by one position toward the end of the list.
No exceptions will occur if you specify an invalid index.
If you specify an index beyond the end of the list, the item will be added to the end
of the list.
If you use a negative index that specifies an invalid position, the item will be inserted
at the beginning of the list.
index(value) Return first index of value. Raises ValueError if the value is not present.
reverse() Reverse the list IN PLACE and return None.
remove(value) Remove first occurrence of value. Raises ValueError if the value is not present.
sort() Sort the list IN PLACE in ascending order and return None.

COMP 125 Programming with Python 46


Example

COMP 125 Programming with Python 47


del Statement

§ In general, del statement is used to delete object references


§ Within the list context, del removes items at specified indices. The indices
of the remaining part are updated!

Reminder:
L.pop(ind) can also be used to remove a list item
Unlike del, L.pop(ind) also returns the popped item

COMP 125 Programming with Python 48


Useful built-in functions: min, max

§ The built-in min and max functions return the item with the minimum and
the maximum value in a list, respectively

COMP 125 Programming with Python 49


Example

§ Write a function that takes a list of exam grades as input, drops the lowest
grade from the list, and returns the remaining list and also the highest
grade. You may assume that the list includes at least two grades.

COMP 125 Programming with Python 50


Example

§ Write a function that takes a string and a character as input; and returns all
words in the string starting with the given character.
§ Your function should be case-insensitive
def words_starting_with(sentence, character):

Sample run:
my_words = words_starting_with('I love ice cream', 'i’)
print(my_words) à ['i', 'ice']

COMP 125 Programming with Python 51


Example (cont’d)

COMP 125 Programming with Python 52


Useful built-in functions

§ The str.join method takes all items in a list (or a sequence) and joins
them into one string.
§ List items should be strings
§ The join method uses a given string as the separator

COMP 125 Programming with Python 53


Example

§ Recall that strings are immutable! What if you want to change a specific
character within the string (let’s say the character at the second index)?

COMP 125 Programming with Python 54


Strings vs. Lists
Strings Lists
olen(), print() olen(), print()
o slicing, indexing o slicing, indexing
o for loops o for loops
o in o in
o concatenation o concatenation
o immutable o mutable
§ Cannot add, remove, or update § append()
elements § pop()
§ assign with indexing
§ del item
COMP 125 Programming with Python 55
List Comprehension
§ An efficient and compact way to create lists
Syntax:
new_list = [expression for member in iterable (if condition)]

§ List comprehension with conditional

COMP 125 Programming with Python 56


List Comprehension Examples

COMP 125 Programming with Python 57


Two-Dimensional Lists
(List of Lists)
Two-dimensional lists

§ Two-dimensional list is a list that contains other lists as its items


§ “List of lists”
§ Also known as nested list
§ Common to think of two-dimensional lists as having rows and columns
§ Useful for working with multiple sets of data

§ To process data in a two-dimensional list, you need to use two indices


§ Have to use valid indices for all of the dimensions

§ Typically, nested loops are used to process a two-dimensional list

COMP 125 Programming with Python 59


Two-dimensional lists

COMP 125 Programming with Python 60


Two-dimensional lists

§ For example, suppose you are writing


a grade-averaging program for an
instructor. The instructor has three
students, and each student takes three
exams during the semester.

COMP 125 Programming with Python 61


Example
>> a = [[1, 2, 3], [4, 5, 6]]

>> a[0]
[1, 2, 3]

>> a[1]
[4, 5, 6]

>> b = a[0]

>> a[0][2]
3

>> a[0][1] = 7

>>a
[[1, 7, 3], [4, 5, 6]]

>> b
[1, 7, 3]
COMP 125 Programming with Python 62
List Comprehension for list of lists
§ Remember creating a list with list comprehension

§ Now let’s create a 5 x 5 matrix filled with 0s

COMP 125 Programming with Python 63


Example
§ Write a program that creates a two-dimensional list with the dimensions of 3
and 4 and fills it with random numbers from 1 to 100.

COMP 125 Programming with Python 64


Example

§ Write a function that takes a 2D list and a value as its inputs;


and replaces all items with the given value with 0.

COMP 125 Programming with Python 65


Example

§ Write a function that takes a 2D list as its input and returns a 1D list containing the
average of each row.

COMP 125 Programming with Python 66


Example

§ Consider two matrices A and B stored as 2D lists (list of lists)


§ A and B have the same number of rows and columns
§ All of their elements are integers or floats
§ Write a function that performs matrix addition to compute C = A + B

COMP 125 Programming with Python 67

You might also like