Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over range(0)

Here is the function:

def is_sorted(L):
    """ (str) -> Bool

    Return True iff the L is sorted in nondecreasing order. Otherwise, return
    False.

    >>> is_sorted([1, 2, 3, 3])
    True
    >>> is_sorted([3, 2, 1, 3])
    False
    """
    if len(L) == 0:
        return False

    for i in range(len(L) - 1):
        if L[i] > L[i + 1]:
            return False

    return True

Then I executed it on a list with one character and it returns True. However, I expected to receive 'list index out of range error'. Could anyone explain why does it behave in such way?

like image 296
Nicko Avatar asked Oct 24 '25 14:10

Nicko


1 Answers

range(a, b, s) is [a, a+s, a+2*s..., x] where x < b.

So range(0) -> range(0,0,1) generates an empty list. This means the inside of the for loop is skipped which returns True.

like image 52
RohithS98 Avatar answered Oct 26 '25 05:10

RohithS98