new to python - re the below code.
I'm confused as to why the index for 7 is [2][2]. I expected it to be [4][0], given that up until this point I had learned that indexes increased by going [0][0], [0][1], [1][0], etc. Any help appreciated - ty.
#Checkpoint 1
incoming_class = [["Kenny", "American", 9], ["Tanya", "Russian", 9], ["Madison", "Indian", 7]]
print(incoming_class)
#Checkpoint 2
incoming_class[2][2] = 8
print(incoming_class)
CodePudding user response:
Think of it this way:
# 0 1 2
incoming_class = [["Kenny", "American", 9], # 0
["Tanya", "Russian", 9], # 1
["Madison", "Indian", 7]] # 2
When we say incoming_class[2][2], we mean to take
- row #2, i.e. the element with index 2 from incoming_class (
["Madison", "Indian", 7])incoming_class[2] == ["Madison", "Indian", 7]
- colmn #2, i.e. the element with index 2 from what we just found (
7).incoming_class[2][2] == 7
CodePudding user response:
As explained in the comment by @cory-kramer you have a list of lists.
Every element of the list is indexed by the first number so [0][x], [1][x], and so on. Because it's a list of lists, every element of the list is actually another list, and it has a number of elements itself indexed by another index so, for the first list you have [0][0], [0][1] and so on.
In your case the element 7 is [2][2]
I suggest checking how lists work in Python here
