File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ Nested Lists
2+ ============
3+
4+ In this chapter you learn:
5+ --------------------------
6+
7+ ==== ==============================================
8+ area topic
9+ ==== ==============================================
10+ ⚙ define a list inside a list
11+ ⚙ index a nested list
12+ 🔀 loop over a nested list
13+ 🔀 create a nested list with a nested loop
14+ ==== ==============================================
15+
16+ Data frequently occurs in the form of tables. To process tables in
17+ Python, we can put lists in other lists. These are called **nested lists **:
18+
19+ .. code :: python3
20+
21+ table = [
22+ ["Emma", 20799],
23+ ["Olivia", 19674],
24+ ["Sophia", 18490],
25+ ["Isabella", 16950],
26+ ["Ava", 15586],
27+ ["Mia", 13442],
28+ ["Emily", 12562],
29+ ]
30+
31+ Generally, for nested lists, the same rules apply as for single lists.
32+ E.g. for the third row:
33+
34+ .. code :: python3
35+
36+ print(table[2])
37+
38+ To access a single element, you need two pairs of square brackets.
39+ E.g. for the second column of the third row:
40+
41+ .. code :: python3
42+
43+ print(table[2][1])
44+
45+ In this chapter we will create and process nested lists.
46+
47+
48+ Exercise 1
49+ ----------
50+
51+ Write all rows of the above table to the screen with a ``for `` loop.
52+
53+ Complete the code:
54+
55+ .. code :: python3
56+
57+ for ... in table:
58+ print(...):
59+
60+
61+ Exercise 2
62+ ----------
63+
64+ Now modify the loop to output only the names.
65+
66+
67+ Exercise 3
68+ ----------
69+
70+ Write each individual *cell * of the table to the screen with a nested ``for `` loop.
71+
72+ Complete the code:
73+
74+ .. code :: python3
75+
76+ for row in ...:
77+ ... cell in row:
78+ print(...)
79+
80+
81+ Exercise 4
82+ ----------
83+
84+ Create an empty table of 10 x 10 cells and fill them with numbers from 1
85+ to 100.
86+
87+ Sort the lines and indent the code properly:
88+
89+ .. code :: python3
90+
91+ for x in range(10):
92+ for y in range(10):
93+ number = 1
94+ number += 1
95+ print(table)
96+ row = []
97+ row.append(number)
98+ table.append(row)
99+ table = []
You can’t perform that action at this time.
0 commit comments