List Slicing

Accessing sublists with slicing

Interview Relevant: Very common in interviews

List Slicing

Extract and modify sublists with slicing.

Code Examples

List slicing techniques.

python
1lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2
3# Basic slicing: lst[start:stop:step]
4lst[2:5]      # [2, 3, 4]
5lst[:5]       # [0, 1, 2, 3, 4]
6lst[5:]       # [5, 6, 7, 8, 9]
7lst[::2]      # [0, 2, 4, 6, 8]
8lst[::-1]     # [9, 8, 7, ...] (reverse)
9
10# Negative indices
11lst[-3:]      # [7, 8, 9]
12lst[:-3]      # [0, 1, 2, 3, 4, 5, 6]
13
14# Slice assignment
15lst[2:5] = [20, 30, 40]
16lst[::2] = [0] * 5  # Every other element
17
18# Delete via slice
19del lst[2:5]
20
21# Copy via slice
22copy = lst[:]

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In