user20939015
user20939015

Reputation:

Can someone explain what the mylist[a][b] does in this Python code?

mylist = [ [2,4,1], [1,2,3], [2,3,5] ]
a=0
b=0
total = 0
while a <= 2:
    while b < 2:
        total += mylist[a][b]
        b += 1
    a += 1
    b = 0 
print (total)

I don't understand what mylist[a][b] does.

I tried adding print statements and checked each of the outputs, but I still can't figure out what it does.

The output with print statement I got was: (each printed output every time it goes through the loop:)

2
4
1
2
2
3
(total)
14

I thought each output were the items inside the lists in mylist, but realized it's not. I also tried changing the numbers inside the lists, I still don't understand. Can someone simply explain it to me please?

Upvotes: 0

Views: 503

Answers (2)

Shounak Das
Shounak Das

Reputation: 368

Okay, You can visualise this code mylist[a][b] as (mylist[a])[b]. So 1st part will get a value of position [a] from my list and then it will get a value of position [b] of mylist[a]. For an example:

mylist = [ [2,4,1], [1,2,3], [2,3,5] ]

Let's say a=1 , b=0 If you want to print mylist[a][b]. It will 1st get [1, 2, 3] then it will get the value at 0 position of the list. So the final output should be 1

Upvotes: 0

JohnFrum
JohnFrum

Reputation: 342

The object between the [ and ] brackets is a "list" and a list can be made of other lists.

When you want to get the value from a list at a particular position, you use the [n] notation, where the n is the position (starting at zero).

If the object at position n is also a list, then you can extract items from that sub-list by again using the square brackets.

So, if I have a list l = [ [1,2,3], [4,5,6] ] then l[0] is equal to [1,2,3] and therefore l[0][1] is equal to 2.

The code you posted is looping over the lists inside the list and then the items inside each of those inner lists.

Upvotes: 1

Related Questions