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

Time:04-18

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 ?

CodePudding user response:

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:])

CodePudding user response:

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.

  • Related