In python lists and tuples can hold lists, tuples, and strings.
"Ana"?"Peter"?23?"Ana"?"Peter"?23?We can often use nested for loops to iterate over nested lists, but we don’t always need nested for loops.
def years_to_months(year):
return year * 12
def change_age(people):
for person in people:
person[1] = years_to_months(person[1])
def to_string(people):
new_string = "Name\tAge\tGrade\n"
for person in people:
for item in person:
new_string += f"{item}\t"
new_string += "\n"
return new_string
if __name__ == "__main__":
people = [["Ana", 34, "B"],
["Peter", 23, "A"],
["Mary", 27, "A"],
["John", 21, "C"]]
change_age(people)
print(people)
print(to_string(people))[['Ana', 408, 'B'], ['Peter', 276, 'A'], ['Mary', 324, 'A'], ['John', 252, 'C']]
Name Age Grade
Ana 408 B
Peter 276 A
Mary 324 A
John 252 C
Write a Python function called calculate_class_average that takes in as argument a nested list representing student grades and calculates the average of the averages. Name your file grade_average.py.
The function should return the average grade across all students in the class (rounded to 2 decimal places).
What will the code below output?
What will the code below output?
With list comprehension:
When copying a list, the nested lists will still refer to the same objects as in the original list.
def create_nested_lists(rows, columns):
return [ [0] * columns for _ in range(rows)]
if __name__ == "__main__":
my_list = create_nested_lists(3, 5)
print(my_list)
another_list = my_list.copy()
another_list[0][0] = -1
print(my_list)[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[[-1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
To recursively copy all objects, you need a deep copy.
import copy
def create_nested_lists(rows, columns):
return [ [0] * columns for _ in range(rows)]
if __name__ == "__main__":
my_list = create_nested_lists(3, 5)
print(my_list)
another_list = copy.deepcopy(my_list)
another_list[0][0] = -1
print(my_list)[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]