List Slicing
List slicing in Python allows you to extract a portion of a list by specifying a range of indices. It is a simple and efficient way to work with multiple elements at once.
Basic Slicing
Basic slicing uses the syntax:
list_name[start:end]
It returns elements from the index up to, but not including, the start index.
end
Example 1:
fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"]
print(fruits[1:4])
Output
['Banana', 'Mango', 'Orange']
Example 2:
numbers = [10, 20, 30, 40, 50]
print(numbers[0:3])
Output
[10, 20, 30]
Start Index
If only the start index is specified, slicing begins from that position and continues to the end of the list.
Syntax:
list_name[start:]
Example 1:
colors = ["Red", "Blue", "Green", "Yellow", "Black"]
print(colors[2:])
Output:
['Green', 'Yellow', 'Black']
Example 2:
numbers = [5, 10, 15, 20, 25]
print(numbers[1:])
[10, 15, 20, 25]
End Index
If only the end index is specified, slicing starts from the beginning of the list and stops before the given end index.
Syntax:
list_name[:end]
Example 1:
fruits = ["Apple", "Banana", "Mango", "Orange"]
print(fruits[:2])
Output:
['Apple', 'Banana']
Example 2:
numbers = [10, 20, 30, 40, 50]
print(numbers[:4])
[10, 20, 30, 40]
Step Value
The step value determines how many positions to skip while slicing.
Syntax:
list_name[start:end:step]
A step value of 2 selects every second element.
Example 1:
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
print(numbers[::2])
Output:
[1, 3, 5, 7]
Example 2:
letters = ["A", "B", "C", "D", "E", "F"]
print(letters[1:6:2])
Output
['B', 'D', 'F']
Reverse a List
A list can be reversed using slicing with a step value of -1.
Syntax:
list_name[::-1]
Example 1:
fruits = ["Apple", "Banana", "Mango", "Orange"]
print(fruits[::-1])
Output
['Orange', 'Mango', 'Banana', 'Apple']
Example 2:
numbers = [10, 20, 30, 40, 50]
print(numbers[::-1])
Output
[50, 40, 30, 20, 10]