I am quite new to python and programming in general so I am still trying to understand the details in practice. This is a problem I found online so I can practice nested loops more. If my question is missing anything or you do not understand my question, please let me know. I would like to get better at asking good questions as well.
list =[[1, 2], [3,4]]
m = 1
print(list)
for i in range(0, 2):
m *= 10
for j in range(0, 2):
list[i][j] *= m # This part right here.
print(list)
This is what prints on the terminal:
[[1, 2], [3, 4]]
[[10, 20], [300, 400]]
I was trying to go through this block of code step by step to make sure I understand it but this part is stumping me. I understand that the whole function of this nested for loop is to multiply the items in the 1st list with 10 and the 2nd list with 100. I also know what the *= m
part is, the part that's confusing to me is the code right before that on the same line.
So far I tried to just copy this specific part in google and see if anything came up. I could not find anything that would make sense. I also tried to just run this whole line and see what printed (list[i][j] *= m
)(I changed the variable to numbers obviously). That only came up with a type error... There are no type variables left in list[2]
. I was trying to isolate it to see what just this part does but it apparently doesn't work like that. I guess i need to think outside the box a little more maybe.
CodePudding user response:
If we take i to be 1 and j to be 1, list[i][j] would be 4. list[i] = [3,4] so what you're doing is finding index 1 of the list [3, 4]
CodePudding user response:
list
is a list containing nested lists.
list[0]
is the list [1, 2]
. list[1]
is the list [3, 4]
.
When you use two indexes like list[i][j]
, it first gets the nested list list[i]
, then accesses the [j]
element of that. So when i == 0
and j == 1
, this accesses the list element containing 2
.
*= m
then multiplies that list element. So when i == 0
and m == 10
, it multiplies the values in the first sublist by 10. Then when i == 1
and m == 100
it multiplies the values in the second sublist by 100.
CodePudding user response:
list = [[1,2], [3,4]]
is an array of arrays.
To get a single element, you have to subscript list
twice, which is exactly what list[i][j]
is.
list[0]
returns [1,2]
, the 0-th element of the list, which is a sublist
list[0][0]
returns 1
, the 0-th element of the 0-th sublist
list[0][1]
returns 2
, the 1st element of the 0-th sublist
.
list[1]
returns [3,4]
, the 1st element of the list, which is a sublist
list[1][0]
returns 3
, the 0-th element of the 1st sublist
list[1][1]
returns 4
, the 1st element of the 1st sublist
.
Also, the reason why list[2]
doesn't return anything is because list
only has two elements, which have the index 0
and 1
, so trying to get the element at index 2
will not work