0

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?

1 Answer 1

1

Because first you check that new_list is not empty, so at least it has a last element. When you remove this check, since your new_list is initially empty, new_list[-1] is out of range.

Sign up to request clarification or add additional context in comments.

1 Comment

@pyn00b that's called short-circuiting. If new_list is empty, the other part of the and will not even be checked and the whole condition is false. On the other hand, if it is true, you know that there is at least one element...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.