List Slicing
M3-R5.1 · Chapter 5: Sequence Data Types · 3 min read
Slicing in List
List slicing in Python is a technique used to extract a subset of elements from a list by specifying a range of indices.
It uses the syntax :
list [ start : stop : step]
- start (inclusive): The index where the slice begins. Defaults to 0.
- stop (exclusive): The index where the slice ends; the element at this index is not included. Defaults to the length of the list.
- step (optional): The interval between elements. Defaults to 1.
Example : =
my_list = [1, 2, 3, 4, 5]
print(my_list[2:4])
Output -
[3,4]
Common Slicing Patterns
|
Slice Syntax |
Description |
|
list1[start:stop] |
Items from index start through stop-1 |
|
list1[start:] |
Items from start through the rest of the list |
|
list1[:stop] |
Items from beginning through stop-1 |
|
list1[:] |
A copy of the whole list |
|
list1[-1] |
Last item in the list |
|
list1[-2:] |
Last 2 items in the list |
|
list1[:-2] |
Everything except the last 2 items |
|
list1[::-1] |
All items in reverse order |
|
list1[1::-1] |
First two items in reverse order |
|
list1[:-3:-1] |
Last two items in reverse order |
|
list1[-3::-1] |
Everything except last two items in reverse order- |
Changing Items in a list
Python lists are mutable, meaning you can modify their contents after they are created.
- Syntax: list_name[index] = new_value
- Example:
fruits = ["apple", "banana", "cherry"]
fruits[1] = "Mango" # Changes "banana" to "Mango"
Output:-
>>> fruits
>>>["apple", "Mango", "cherry"]
- Syntax: list_name[start:end] = [new_values]
- Example:
numbers = [10, 20, 30, 40, 50]
numbers[1:3] = [21, 31] # Replaces index 1 and 2 (20 and 30)
Output :-
>>>numbers
>>>[10,21,31,40,50],