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.