Given a list of integers:
old_list = [1,1,2,-2,5,2,4,4,-1,-2,5]
I run the following code to get all the integers grouped in a list of lists:
old_list.sort()
new_list = []
for i in old_list:
if new_list == []:
new_list.append([i])
elif new_list[-1][0] == i:
new_list[-1].append(i)
else:
new_list.append([i])
print(new_list)
Returning my desired output:
[[-2, -2], [-1], [1, 1], [2, 2], [4, 4], [5, 5]]
On the one hand I found I could condense the if elif statement using and, while retrieving the same output:
old_list.sort()
new_list = []
for i in old_list:
if new_list and new_list[-1][0] == i:
new_list[-1].append(i)
else:
new_list.append([i])
print(new_list)
On the other hand if I try to remove the new_list and from the if statement the following error arises:
IndexError: list index out of range
Why isn't the if new_list and new_list[-1][0] == i: statement firing the same index error?