Python Slicing Worksheet with Answers
Part A - String Slicing
Let s = "PythonIsFun"
1. First 6 characters
2. Last 3 characters
3. Characters from index 3 to 7
4. Reverse the string
s = "PythonIsFun"
print(s[:6]) # Python
print(s[-3:]) # Fun
print(s[3:8]) # honIs
print(s[::-1]) # nuFnsInohtyP
Part B - List Slicing
Let lst = [10, 20, 30, 40, 50, 60, 70]
5. First 4 elements
6. Last 2 elements
7. Every 2nd element
8. Reverse the list
9. Elements from index 2 to 5
lst = [10, 20, 30, 40, 50, 60, 70]
print(lst[:4]) # [10, 20, 30, 40]
print(lst[-2:]) # [60, 70]
print(lst[::2]) # [10, 30, 50, 70]
print(lst[::-1]) # [70, 60, 50, 40, 30, 20, 10]
print(lst[2:6]) # [30, 40, 50, 60]
Part C - Tuple Slicing
Let t = (100, 200, 300, 400, 500, 600)
10. Print (200, 300, 400)
11. Reverse the tuple
12. Every second element in reverse
t = (100, 200, 300, 400, 500, 600)
print(t[1:4]) # (200, 300, 400)
print(t[::-1]) # (600, 500, 400, 300, 200, 100)
print(t[::-2]) # (600, 400, 200)
Part D - Challenge Questions
Let s = "DataStructures"
13. Extract "Structures" using negative indexing
14. Print all characters at even indexes in reverse
15. Input a string and:
a) Reverse it
b) Print characters from 2nd to 2nd last with a step of 2
s = "DataStructures"
print(s[-10:]) # Structures
print(s[::-2]) # sertrtDt
# Q15
text = input("Enter a string: ")
print(text[::-1])
print(text[1:-1:2])
Bonus Problem
Let marks = [95, 87, 76, 65, 88, 91, 73]
16. Print top 3 marks using slicing (without sorting the original list)
marks = [95, 87, 76, 65, 88, 91, 73]
top3 = sorted(marks, reverse=True)[:3]
print(top3) # [95, 91, 88]