What do the numbers mean in the function range(len(sequence)-1,0,-1) mean?

Viewed 1916

I am currently being tasked with writing the bubble sort algorithm in python and one of the solutions I have come across contains this piece of code.

for passnum in range(len(alist)-1,0,-1):
    for i in range(passnum):
        if alist[i]>alist[i+1]:
            temp = alist[i]
            alist[i] = alist[i+1]
            alist[i+1] = temp

In line 1 the range is specified with -1,0,-1 and I don't know why or what this does and was wondering if anyone could help out? Thanks.

3 Answers

range(len(alist)-1,0,-1) returns a range of integers starting at len(alist) - 1, continuing utill it hits 0, and increasing by -1 (decreasing by 1) each iteration.

The first for loop is using this range statement to start at the end of alist (index len(alist) -1) and work backwards to the start (index 0), one item at a time. The second for loop is starting at 0 and counting up to passnum - your code is checking the entire list first, then everything but the last element of the list, then everything but the second-to-last, and so on.

This implementation of Bubblesort is pushing the largest element to the end of the array - since we know the largest one will be at the end after each pass of the first for loop, there's no need to compare the next element to be sorted to the end of the list.

would like to add some more informations to above answers from the python documentation

https://docs.python.org/3/library/stdtypes.html#range

range(stop) range(start, stop[, step]) Rather than being a function, range is actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.

Example:

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))
[]

if len(alist) = 10

range(len(alist)-1,0) would mean []

range(len(alist)-1,0,-1) the -1 indicated you subtract(-1) from len(alist)-1 till it reached 1, which would mean the sequence will be [9, 8, 7, 6, 5, 4, 3, 2, 1]

Related