List Indexing and Slicing
Precisely accessing and extracting parts of a list — from single items to entire sub-sections using Python's powerful slice notation.
"Indexing gets you one item. Slicing gets you any portion you want. Together, they let you work with exactly the data you need."
— ShurAIPositive Indexing — Counting from the Start
Every item in a list has a position number starting from 0. Use square brackets to grab any item by its position:
colours = ["red", "green", "blue", "yellow", "purple"]
print(colours[0]) # red — first
print(colours[2]) # blue — third
print(colours[4]) # purple — fifth (last)
print(colours[-1]) # purple — last (negative)
print(colours[-2]) # yellow — second from last
Slicing — Grab a Section
Slicing uses [start:stop] — start is included, stop is not included. Think of it as cutting out a portion of the list:
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
print(days[0:3]) # ['Mon', 'Tue', 'Wed'] — index 0,1,2
print(days[5:]) # ['Sat', 'Sun'] — index 5 to end
print(days[:5]) # ['Mon','Tue','Wed','Thu','Fri'] — start to 4
print(days[1:4]) # ['Tue', 'Wed', 'Thu']
print(days[-2:]) # ['Sat', 'Sun'] — last 2
print(days[:]) # full copy of the list
Step Slicing — Every Nth Item
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [start:stop:step]
print(nums[0:10:2]) # [0, 2, 4, 6, 8] — every 2nd
print(nums[::3]) # [0, 3, 6, 9] — every 3rd
print(nums[::-1]) # [9, 8, 7, ... 0] — reversed!
print(nums[8:2:-1]) # [8, 7, 6, 5, 4, 3] — backwards slice
Modifying with Slices
You can replace a whole section of a list in one go:
letters = ["a", "b", "c", "d", "e"]
# Replace a slice with new values
letters[1:3] = ["X", "Y", "Z"]
print(letters) # ['a', 'X', 'Y', 'Z', 'd', 'e']
# Delete a slice
del letters[1:4]
print(letters) # ['a', 'd', 'e']
Real Example — Top 3 and Bottom 3 Students
students = [
("Kavya", 95),
("Riya", 88),
("Arjun", 82),
("Sneha", 76),
("Dev", 71),
("Priya", 65),
("Vikram", 58),
]
# Sort by score descending
ranked = sorted(students, key=lambda x: x[1], reverse=True)
# Slice to get top 3 and bottom 3
top3 = ranked[:3]
bottom3 = ranked[-3:]
print("🏆 Top 3:")
for i, (name, score) in enumerate(top3, 1):
print(f" {i}. {name} — {score}")
print("\n📚 Need extra help:")
for name, score in bottom3:
print(f" {name} — {score}")
🏆 Top 3:
1. Kavya — 95
2. Riya — 88
3. Arjun — 82
📚 Need extra help:
Dev — 71
Priya — 65
Vikram — 58
"Slicing is your scalpel. Instead of grabbing the whole list and filtering, you cut out exactly what you need in one clean line."
— ShurAI🧠 Quiz — Question 1
Given items = [10, 20, 30, 40, 50], what does items[1:4] return?
🧠 Quiz — Question 2
Given x = [1, 2, 3, 4, 5], what does x[-2:] return?
🧠 Quiz — Question 3
What does [1,2,3,4,5,6][::-1] return?
🧠 Quiz — Question 4
Given n = [0,1,2,3,4,5,6,7,8,9], what does n[::2] return?