Python Slicing Exercises

Let’s check out some exercises that will help you understand and master how Python’s Slice Notions, Slicing and Advanced Slicing works.

Exercise 17-a

Slice the word until first "a". (Tosc)


[start:stop] notation can be used to slice a Python string.

Just keep in mind that in [start:stop] notation, stop value won’t be included. So, you need to type the index of the last value you’d like to include +1.

ans_1 = wrd[0:4]

or

ans_1 = wrd[:4]

or

ans_1 = wrd[:4:1]

Exercise 17-b

Slice the word so that you get "cana".


[start:stop] notation can be used to slice a Python string.

Just keep in mind that in [start:stop] notation, stop value won’t be included. So, you need to type the index of the last value you’d like to include +1.

ans_1 = wrd[3:]

or

ans_1 = wrd[3::1]

Exercise 17-c

Now try to get "can" only.


[start:stop] notation can be used to slice a Python string.

Just keep in mind that in [start:stop] notation, stop value won’t be included. So, you need to type the index of the last value you’d like to include +1.

ans_1 = wrd[3:-1]

or

ans_1 = wrd[3:6]

Exercise 17-d

Can you slice the word from beginning to the end with steps of 2 (including the last character.)?


[start:stop] notation can be used to slice a Python string.

Just keep in mind that in [start:stop] notation, stop value won’t be included. So, you need to type the index of the last value you’d like to include +1.

If you omit the parameter before the colon (:) It will mean all the way for that parameter.

So, [:3:1], here first colon has no parameter which means all the way from the beginning. And, [0::1] here second colon has no parameter which means all the way to the end.

ans_1 = wrd[::2]

or

ans_1 = wrd[0::2]

Exercise 17-e

Now slice the word with steps of 2, excluding first and last characters.


[start:stop] notation can be used to slice a Python string.

Just keep in mind that in [start:stop] notation, stop value won’t be included. So, you need to type the index of the last value you’d like to include +1.

ans_1 = wrd[1:-1:2]

Exercise 17-f

Can you slice the list so that it's reversed without using the .reverse() method?


[start:stop] notation can be used to slice a Python string.

Just keep in mind that in [start:stop] notation, stop value won’t be included. So, you need to type the index of the last value you’d like to include +1.

ans_1 = lst[::-1]

Exercise 17-g

Slice the list so that only last 2 elements are included.


You can start from “second element from the last” and go all the way to the end.

ans_1 = lst[-2:]

or

ans_1 = lst[-2::1]

Exercise 17-h

Slice the second and third elements (50 and 20) in the list.


Indexing starts with 0. So, index 0 is the first element in the list.

ans_1=lst[1:3]