Can the start or end of a list slice contain a negative number?


#1

Question

Can negative numbers be used for the start or end points of a slice?

Answer

Yes, negative numbers can be used for the start or end of a list slice. A negative number used for the start of the slice will return a list which contains the number of items starting from the end of the list. A negative number used for the end returns a list which contains items excluding the number of items at the end of the list.

The following example shows both cases.

colors = ['red', 'green', 'blue', 'yellow', 'orange']

# List containing only last 2 = ['yellow', 'orange']
print(colors[-2:])

# List excluding last 2 = ['red', 'green', 'blue']
print(colors[:-2])