08 - Lists
08 - Lists
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.
§ In Python, the most basic, and arguably one of the most useful, collection is
the List data structure
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
§ Write a code fragment that calculates the sum of the items in a given list
§ 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
Alternative implementation
§ 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
§ 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.
for i in range(len(unique_res)):
for j in range(len(protein)):
if protein[j] == unique_res[i]:
freq[i] += 1
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
§ Concatenate: Join two things together (you have seen the string version)
Output
[1, 2, 3, 4]
[99, 2, 3, 4]
Output
[1, 2, 3, 4]
[99, 2, 3, 4]
list2[0] = 99
print(list1)
print(list2)
Output
[1, 2, 3, 4]
[99, 2, 3, 4]
§ To preserve the original list, you can use the slicing operation
§ 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.
§ Write another function that takes a list containing students’ grades as input,
computes the average grade, and returns it.
§ 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.
§ 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.
§ The * operator makes multiple copies of a list and joins them all together
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.
Reminder:
L.pop(ind) can also be used to remove a list item
Unlike del, L.pop(ind) also returns the popped item
§ The built-in min and max functions return the item with the minimum and
the maximum value in a list, respectively
§ 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.
§ 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']
§ 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
§ 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)?
>> 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
§ Write a function that takes a 2D list as its input and returns a 1D list containing the
average of each row.