Nested Lists
An element of a list can be any value, even another list. A list inside a list is called a nested list. Nested lists are useful for data that comes in groups, such as study groups:
study_groups = [["Jennifer", "Boris"], ["David", "Ava", "Nancy"]]
print(study_groups)This prints:
[['Jennifer', 'Boris'], ['David', 'Ava', 'Nancy']]The list study_groups has two elements, and each of them is a list of names: one study group. The first index selects a group, which is an ordinary list:
print(study_groups[1])This prints:
['David', 'Ava', 'Nancy']To get one student, add a second index in square brackets. study_groups[1][0] first takes the element at index 1 (the second group, ["David", "Ava", "Nancy"]) and then, from that list, the element at index 0:
print(study_groups[1][0])This prints:
DavidEverything you know about lists works for the inner lists too. len(study_groups) is 2, the number of groups, while len(study_groups[1]) is 3, the number of students in the second group. study_groups[0][-1] is the last student of the first group, "Boris". And study_groups[0].append("Tim") adds Tim to the end of the first group.
Instructions
Print the first member of the second team. Use two indexes.
Tim has joined the first team. Add "Tim" to the end of the first team, teams[0], with append().
Print the whole list teams. The output should be [['Peter', 'Lucy', 'Tim'], ['Daniel', 'Ava']].
Start programming for free
10/12