0
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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 2
    `mylist[a]` will be one of the 3 sublists in `mylist`, and `mylist[a][b]` will be one of the 3 numbers inside that sublist. Is that what you want to know? – mkrieger1 Jan 05 '23 at 17:50
  • Look at it as a matrix. `Mylist[0]` is your first array which is [2,4,1] here mylist[0][0] is 2,mylist[0,1] is 4 and mylist[0,2] is 1 from [2,4,1]. – Luff li Jan 05 '23 at 17:55
  • @mkrieger1 yes, oh god I feel so embarrassed with getting confused with it thank you so much, thanks also for editing my question –  Jan 05 '23 at 18:11
  • I'm voting to close as duplicate of [Nested lists python](https://stackoverflow.com/questions/8189169/nested-lists-python) – mkrieger1 Jan 05 '23 at 18:19

2 Answers2

1

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.

JohnFrum
  • 343
  • 2
  • 9
  • 1
    thank you so much for such simple and complete explanation, I already know the answer to my question even before I get to read your example because of your explanations, thank you so much!! –  Jan 05 '23 at 18:13
0

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

Shounak Das
  • 350
  • 12