'Can someone explain me why when the following code run it shows just empty square bracket?

x = [65,78,99,43,23,45,87,96,33,42]

random = print(x[0:4])
[65, 78, 99, 43]

random = print(x[-1:-4])
[]                       

so my question is why they show empty brackets ?



Solution 1:[1]

The starting point should be before the ending point, that's not the case here, so the slice (the sublist) is empty as no value is between the given boundaries

[65,78,99,43,23,45,87,96,33,42]
                   -4       -1
                   end     start

to print 4 lasts

print(x[-4:])

Solution 2:[2]

You cannot index backwards the same way as you would forwards. This is because even though while going backwards the -1 index comes first, in the array itself the value at -4 comes before the last value. To print that just go print(x[-4:]). This goes from the index of -4 all the way to the end of the array.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 azro
Solution 2 diana18