Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Once you have created a list of data, the next fundamental task is retrieving specific items from it. Whether you need the very first element, the last element, or a subset of values, Python provides an elegant and expressive indexing and slicing syntax.
Unlike languages that only allow zero-to-positive counting, Python features native negative indexing (counting backwards from the end) and stride slicing ([start:stop:step]), making sequence manipulation effortless and concise.
+-------------------------------------------------------------------------+
| LIST ACCESSING REAL-WORLD ANALOGY |
+-------------------------------------------------------------------------+
1. THE CRICKET BATTING ORDER (Positive & Negative Positions):
- In the Indian ODI squad, the batting order has 11 players.
- Positive Index 0 is the opening batsman (e.g., Rohit Sharma).
- Positive Index 1 is the second opener (e.g., Shubman Gill).
- What if you want to inspect the final tailender bowler?
Instead of calculating len(team) - 1, Python gives you negative index:
team[-1] is the last player, and team[-2] is the second-to-last!
2. BANK DEPOSIT LOCKER GRID (Direct O(1) Index Access):
- When you visit a bank vault in Mumbai, each locker has a stamped number.
- With your key number [3], you open locker 3 in constant time O(1).
- You don't have to inspect lockers 0, 1, and 2 first.
3. METRO TRAIN JOURNEY SLICE (start:stop):
- If you board a train from Station 2 up to Station 6, you ride through
stations 2, 3, 4, and 5. Station 6 is where you exit—it is excluded!
+-------------------------------------------------------------------------+Every item in a Python list occupies an addressable slot. Accessing an element via its index runs in constant $O(1)$ time complexity.
[start : stop : step]Slicing extracts a sub-list without modifying the original parent list. The syntax follows: $$\text{list}[\text{start} : \text{stop} : \text{step}]$$
start: Index where extraction begins (inclusive, defaults to 0).stop: Index where extraction terminates (exclusive, defaults to len(list)).step: Stride or interval between elements (defaults to 1).in and not inBefore accessing an element or searching for its position, you can verify its presence using membership operators in clean, idiomatic English:
| Scenario | ❌ Anti-Pattern | ✅ Pythonic Idiom |
|---|---|---|
| Last Element Access | items[len(items) - 1] | items[-1] (Direct negative index) |
| First N Elements | items[0:n] | items[:n] (Omit redundant 0) |
| Cloning a List | Iterating with loop + append | clone = items[:] or items.copy() |
| Reversing Elements | items.reverse() when wanting new copy | reversed_items = items[::-1] |
| Out-of-Bounds Check | Unchecked direct index | Check 0 <= index < len(items) or try...except IndexError |
| Find Item Existence | try: items.index(x) | if x in items: (Membership operator) |
+---------------------------------------------------------------------------+ | LIST INDEXING & SLICING CHEAT SHEET | +---------------------------------------------------------------------------+ | Syntax | Operation / Return Value | |-----------------------+---------------------------------------------------| | list[0] | First element of the list | | list[-1] | Last element of the list | | list[-2] | Second to last element | | list[:k] | First k elements (from index 0 to k-1) | | list[k:] | Elements from index k through the very end | | list[a:b] | Slice from index a (inclusive) to b (exclusive) | | list[::2] | Every 2nd element starting at 0 | | list[::-1] | Reversed copy of the list | | list[:] | Complete shallow copy of the list | | x in list | Returns True if x is present in list | | list.index(x) | Returns index of first occurrence (or ValueError) | +---------------------------------------------------------------------------+
Assigning list_b = list_a does NOT create a copy; both variables point to the same memory object:
Accessing an index equal to or greater than len(my_list) raises IndexError:
cities = ["Delhi", "Mumbai", "Kolkata", "Chennai", "Bengaluru"], what does cities[-1] return?A. "Delhi" B. "Chennai" C. "Bengaluru" D. IndexError
numbers[1:4] on numbers = [10, 20, 30, 40, 50, 60]?A. [10, 20, 30] B. [20, 30, 40] C. [20, 30, 40, 50] D. [10, 20, 30, 40]
data = [1, 2, 3, 4] using slicing?A. data[0:-1] B. data[::-1] C. data[-1:0] D. data[-1:-4]
items[10] on a list containing only 4 items?A. Python returns None B. Python returns an empty list [] C. Python raises an IndexError: list index out of range D. Python extends the list with empty slots
letters[::2] produce when letters = ['A', 'B', 'C', 'D', 'E']?A. ['A', 'B'] B. ['A', 'C', 'E'] C. ['B', 'D'] D. ['C', 'D', 'E']
Write a Python script that takes a list of semester exam marks for 8 subjects, extracts the top 3 highest scores using sorting and slicing, grabs the bottom 2 scores with negative slicing, and reverses the chronological score list.
In the next lesson, we will continue your Python learning journey with Add & Remove Items (8: Lists).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| List Introduction | Add & Remove Items |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.