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
my_list[2:8]
do?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
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)
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)