0
0
Pythonprogramming~5 mins

Nested lists in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a nested list in Python?
A nested list is a list that contains other lists as its elements. It's like a box inside another box, where each inner box can hold items.
Click to reveal answer
beginner
How do you access an element inside a nested list?
You use multiple square brackets. The first bracket selects the inner list, and the second bracket selects the element inside that inner list. For example, list[0][1] accesses the second item of the first inner list.
Click to reveal answer
intermediate
How can you add an element to an inner list inside a nested list?
First, access the inner list using its index, then use the append() method. For example, nested[1].append(5) adds 5 to the second inner list.
Click to reveal answer
beginner
What does this code output?
nested = [[1, 2], [3, 4]]
print(nested[1][0])
It outputs 3 because nested[1] is the second inner list [3, 4], and nested[1][0] is the first element of that list, which is 3.
Click to reveal answer
beginner
Can nested lists have different lengths for inner lists?
Yes! Inner lists can have different numbers of elements. For example, [[1, 2], [3, 4, 5]] is valid.
Click to reveal answer
What is the output of this code?
lst = [[10, 20], [30, 40]]
print(lst[0][1])
A20
B10
C30
D40
How do you add the number 5 to the second inner list in nested = [[1], [2, 3]]?
Anested[0].append(5)
Bnested.append(5)
Cnested[1][5]
Dnested[1].append(5)
Which of these is a valid nested list?
A[1, 2, 3, 4]
B[[1, 2], [3, 4, 5]]
C[[1, 2], 3, 4]
D[1, [2, 3], 4]
What does nested[2][0] do if nested = [[1], [2, 3]]?
AReturns 2
BReturns 1
CCauses an error because nested has no third inner list
DReturns 3
How can you print all elements of a nested list nested = [[1, 2], [3, 4]]?
AUse two loops: for inner in nested: for item in inner: print(item)
BUse one loop: for item in nested: print(item)
CUse nested.print()
DUse nested.flatten()
Explain what a nested list is and how you access elements inside it.
Think of a list inside another list like boxes inside boxes.
You got /3 concepts.
    Describe how to add an element to an inner list within a nested list.
    First find the right inner list, then add the item.
    You got /3 concepts.