Python Slicing Tutorial

1. Slicing Lists

Lists in Python can be sliced using the start:stop:step notation.

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_list[2:8]) # Slicing from index 2 to 7
print(my_list[:5]) # Slicing from start to index 4
print(my_list[5:]) # Slicing from index 5 to end
print(my_list[::2]) # Slicing with a step of 2
[2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]
Q: What does my_list[2:8] do?
A: It slices the list from index 2 to 7 (the stop index is exclusive).

2. Slicing Tuples

Tuples can be sliced in a similar way to lists.

my_tuple = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
print(my_tuple[2:8]) # Slicing from index 2 to 7
print(my_tuple[:5]) # Slicing from start to index 4
print(my_tuple[5:]) # Slicing from index 5 to end
print(my_tuple[::2]) # Slicing with a step of 2
(2, 3, 4, 5, 6, 7)
(0, 1, 2, 3, 4)
(5, 6, 7, 8, 9)
(0, 2, 4, 6, 8)
Q: Can you modify the sliced tuple?
A: No, tuples are immutable. You can slice them but cannot modify the elements.

3. Slicing Dictionaries

Dictionaries do not support slicing directly, but you can use loops to achieve similar results.

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
keys = list(my_dict.keys())
sliced_keys = keys[1:4] # Slicing keys from index 1 to 3
sliced_dict = {key: my_dict[key] for key in sliced_keys}
print(sliced_dict)
{'b': 2, 'c': 3, 'd': 4}
Q: How can you slice a dictionary to get only specific keys?
A: Convert the keys to a list, slice the list, then create a new dictionary with the sliced keys.

4. Using Loops for Slicing

Sometimes, using loops can be helpful for more complex slicing operations.

my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
sliced_list = []
for i in range(1, len(my_list), 3):
sliced_list.append(my_list[i])
print(sliced_list)
[20, 50, 80]
Q: What does the loop in the example do?
A: It appends every third element starting from index 1 to a new list.