0

To get [[1, 1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]

from old_list = [1,1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]

I found this answer:

new_list = []
for value in old_list:
    if new_list and new_list[-1][0] == value:
        new_list[-1].append(value)
    else:
        new_list.append([value])

I am trying to understand what is meaning of new_list[-1][0] confusion came when I tried to run

new_list = []
new_list[-1] # shows index out of bounds

and new_list and new_list[-1][0] does not produce any error under if statement

What new_list[-1][0] is doing here.

3 Answers3

1

new_list[-1][0] retrieves the last element of new_list, which is itself a list and gets its first element.

new_list and new_list[-1][0] == value short circuits, so it does not try to access the last element if the list is empty.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

new_list[-1][0] is checking for the first value in the last element of the list new_list.

Example:

For new_list = [[1, 1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]

if you try new_list[-1][0], you will get value 5.

[-1] gets you the last element of the list and [0] gives you the first value.

So, [-1] gets you [5,5,5,5,5] and then [0] gives yoou 5.

Prashant Kumar
  • 2,057
  • 2
  • 9
  • 22
0

Say we tried something on a normal list like this.

new_list = [1,2,3]
print(new_list[-1][0])

We are going to receive an error

    print(new_list[-1][0])
TypeError: 'int' object is not subscriptable

But if we try indexing that on lists of a list it will work.

new_list = [[1,2,3],[4,5,6]]
print(new_list[-1][0])

no error, output is

4

Lets take a look into list[-1][0]. Basically, [-1] will get us the last element in a list. In this case it will give us the last list in our bigger list. Then the [0] will get us the first element in a list. So the order is [4,5,6] & 4

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44