⊗pyPmSlNP 80 of 208 menu

Slice with Negative Positions in Python

In slices, you can also access elements by negative indices. In this case, they will be counted from the end of the sequence. Let's make a slice from the third to the penultimate element:

txt = '123456789' res = txt[2:-1] print(res) # '345678'

Given a string:

txt = '123456789'

Get the following slice from it:

'567'

Given a list:

lst = ['a', 'b', 'c', 'd', 'e', 'f']

Get the following slice from it:

['b', 'c', 'd']

Given a list:

lst = ['a', 'b', 'c', 'd', 'e', 'f']

Get the following slice from it:

['f']
byenru