Python List Slicing
Python List Slicing
In Python, list slicing uses the syntax L[start:stop] to extract a subset of elements.Python list slicing is a powerful feature that allows you to extract specific portions of a list using a concise and readable syntax. This technique is essential for accessing, modifying, and manipulating elements within a list.
Basic Syntax
The general syntax for slicing a list is:
list[start:end:step]
start: The index at which the slice begins (inclusive). If omitted, it defaults to the beginning of the list.
end: The index at which the slice ends (exclusive). If omitted, it defaults to the end of the list.
step: The interval between elements in the slice. If omitted, it defaults to 1.
Example
Let’s understand how it works with the help of an example:
Given a list, what would be output of the code:
L=[10,20,30,40,50,60]
print(L[2:-2])
The list is defined as L = [10, 20, 30, 40, 50, 60]
Python list indices start at 0, so the elements have these indices:
Index 0: 10
Index 1: 20
Index 2: 30
Index 3: 40
Index 4: 50
Index 5: 60
Slicing L[2:-2]:
The slice starts at index 2, which is the element 30.
The slice stops at index -2. In Python, negative indices count from the end, so index -2 corresponds to the element at index 4 (since 6 + (-2) = 4), which is 50. However, the stop index is not included in the slice.
This means the slice includes elements at indices 2 and 3 only:
Index 2: 30
Index 3: 40
Result:
The output of print(L[2:-2]) is the list [30, 40].