Indexing

🔢 Indexing lets you access elements inside sequences and containers like strings, lists, tuples, and dictionaries. It’s like picking specific items out of a box—once you master it, you’ll access data with precision and speed.

1 Zero-Based Indexing

Python uses zero-based indexing, meaning the first element has index 0.

cool_electives = ['Deep Learning', 'Algorithm Design', 'Reinforcement Learning']

print(cool_electives[0])  # Deep Learning
print(cool_electives[1])  # Algorithm Design
print(cool_electives[2])  # Reinforcement Learning
Deep Learning
Algorithm Design
Reinforcement Learning
elective = 'Deep Learning'

print(elective[0])  # D
print(elective[4])  # 
D
 

2 Negative Indexing

Negative indices start from the end of the sequence, with the last element having index -1.

elective = "Algorithm Design"

print(elective[-1])  # n
print(elective[-2])  # g
print(elective[-3])  # i
n
g
i

3 Multi-Level Indexing

Access nested structures by chaining indices.

electives = [['Deep Learning', 'Algorithm Design'], ['Cloud Computing']]

print(electives[0])     # ['Deep Learning', 'Algorithm Design']
print(electives[0][0])  # Deep Learning
print(electives[1][0][0])  # C
['Deep Learning', 'Algorithm Design']
Deep Learning
C

4 Slicing

Use start:stop to get a portion of a sequence. The stop index is exclusive (not including).

course_codes = [6101, 6103, 6303, 6450, 6501]
print(course_codes[2:10])   # [6303, 6450, 6501]
print(course_codes[:3])    # [6101, 6103, 6303]
print(course_codes[4:])    # [6501]
print(course_codes[:])     # [6101, 6103, 6303, 6450, 6501]
print(course_codes[-3:])   # [6303, 6450, 6501]
[6303, 6450, 6501]
[6101, 6103, 6303]
[6501]
[6101, 6103, 6303, 6450, 6501]
[6303, 6450, 6501]
elective = "Reinforcement Learning"
print(elective[1:4])   # ein
print(elective[::-1])  # gninraeL tnemecrofnieR
ein
gninraeL tnemecrofnieR

Common Indexing Errors

Some frequent errors encountered when dealing with Indexing in Python.

electives = ['Deep Learning', 'Algorithm Design', 'Reinforcement Learning']
print(electives[3])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[7], line 2
      1 electives = ['Deep Learning', 'Algorithm Design', 'Reinforcement Learning']
----> 2 print(electives[3])

IndexError: list index out of range