x=“akshay”

print(x[ : -2]

output is aksh

1 Like

@akshay.inamdar1995

mylist = [1,2,3,4,5,6,7,8,9,10]

mylist[-2] is equivalent to mylist[10–2] = mylist[8]

Now, given problem is to compute mylist[:-2].

First parameter is omitted. It means first parameter is 0.

Second parameter is negative. It means the original index will be (10–2) = 8.

Thus, mylist[:-2] is equivalent to mylist[0:8],

mylist[0:8] returns the first eight elements of the list i.e [1, 2, 3, 4, 5, 6, 7, 8]. The expression in problem returns the list with the last element and second last element omitted.

Therefore, x[:-2] returns all elements in order except the last element and second last element.

3 Likes