List slicing in Python allows you to create a new list by extracting a portion of an existing list using the colon notation (:). The syntax for slicing is:
list[start:stop:step]
start: The index where the slice begins (inclusive).stop: The index where the slice ends (exclusive).step: The interval between each index in the slice (optional).
Here’s an example:
my_list = [10, 20, 30, 40, 50, 60, 70]
# Slicing to get elements from index 1 to 4
sliced_list = my_list[1:5] # [20, 30, 40, 50]
# Slicing with a step
sliced_with_step = my_list[::2] # [10, 30, 50, 70]
# Slicing with negative indices
sliced_negative = my_list[-4:-1] # [40, 50, 60]
print(sliced_list)
print(sliced_with_step)
print(sliced_negative)
This will output:
[20, 30, 40, 50]
[10, 30, 50, 70]
[40, 50, 60]
You can also omit any of the parameters to use default values. For example, my_list[:3] will give you the first three elements, and my_list[3:] will give you all elements from index 3 to the end.
