Imagine you’re at a concert. You bought a ticket, and your seat number is 42. That number matters if you sit in seat 43, someone might yell at you.
In programming, sequences work the same way they are ordered collections where position matters. If you mess up the position, you get the wrong data.
Let’s break this concept down, go deeper into how sequences actually work, and even build our own custom sequence class because why not have some fun with Python?
🔹 What is a Sequence (Really)?
A sequence is just an ordered collection of items that:
✅ Stores data in order
✅ Lets you access elements by position (index)
✅ Can be iterated over (looped through)
Think of it like a train 🚆 each compartment (element) has a position, and you can walk through them one by one.
🛠️ Built-in Sequences in Python
-
list
→[1, 2, 3]
(mutable you can change it) -
tuple
→(1, 2, 3)
(immutable can’t change it) -
str
→"hello"
(sequence of characters) -
range
→range(5)
(sequence of numbers, great for loops)
🌍 In Other Languages
-
JavaScript →
Array
,String
-
Java →
Array
,ArrayList
- C/C++ → Arrays (closer to raw memory)
🔹 Why Do Sequences Start at Index 0
?
This is a question every beginner asks at least once. Here’s the deep dive:
🧠 Memory-Level Explanation
In low-level languages like C, an array name is basically a pointer it stores the memory address of the first element.
When you access array[0]
, this is equivalent to:
*(array + 0) # "Take the value at array + offset 0"
✅ Index 0 means:
“Start at the beginning. No offset. No extra calculation.”
If we started indexing at 1, every access would internally need to do index - 1
. That’s wasted CPU cycles.
⚡ Benefits of 0-based Indexing
- Faster and Simpler → No extra math for offsets
- Pointer Arithmetic Friendly → Makes sense at machine level
- Consistent Across Data Structures → Arrays, stacks, queues, heaps all work smoothly
-
Better Math for Slicing → Example:
len(my_list)
= number of elements → last index =len(my_list) - 1
🎯 Real Life Example
Imagine your house has rooms numbered starting from 1.
But the blueprint (your builder’s design) starts counting from 0 (because it’s measuring distance from the start of the plot).
Programming languages think like the blueprint they care about offsets from the start, not arbitrary numbers.
🔹 Slicing Like a Pro in Python
Python makes it ridiculously easy to grab parts of a sequence using slicing:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # [20, 30, 40] (from index 1 to 3)
print(numbers[:3]) # [10, 20, 30] (start from 0)
print(numbers[::2]) # [10, 30, 50] (step by 2)
print(numbers[::-1]) # [50, 40, 30, 20, 10] (reversed!)
🧩 How Slicing Works Internally
sequence[start:stop:step]
-
start
→ where to begin -
stop
→ where to stop (but not include) -
step
→ how much to jump each time
Fun fact: You can use .indices()
on a slice object to see how Python resolves it!
🔹 Copying Sequences Safely
Want to copy a list without messing up the original? Here’s how:
original = [1, 2, 3]
copy1 = original[:] # slicing
copy2 = list(original) # list constructor
copy3 = original.copy() # list method
⚠️ Warning: These are shallow copies → nested lists still share memory.
For deep copies:
import copy
nested = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(nested)
nested[0][0] = 999
print(deep_copy[0][0]) # Still 1 ✅
🔹 Build Your Own Sequence (Super Fun!)
Let’s create a custom sequence that always repeats a value.
class RepeatedSequence:
def __init__(self, value, count):
self.value = value
self.count = count
def __len__(self):
return self.count
def __getitem__(self, index):
if isinstance(index, slice):
start, stop, step = index.indices(self.count)
return [self.value for _ in range(start, stop, step)]
if index < 0:
index += self.count
if 0 <= index < self.count:
return self.value
raise IndexError("Index out of range")
def __repr__(self):
return f"{[self.value] * self.count}"
🎮 Usage
seq = RepeatedSequence("🍕", 5)
print(seq[2]) # 🍕
print(seq[:3]) # ['🍕', '🍕', '🍕']
print(len(seq)) # 5
🔹 Bonus: Use collections.abc.Sequence
If you inherit from Sequence
, you get __contains__
, __iter__
, .index()
, .count()
for free!
from collections.abc import Sequence
class MySeq(Sequence):
def __init__(self, data):
self.data = data
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return len(self.data)
📘 Summary
✅ Sequence = Ordered Collection → lets you access data by position
✅ Index Starts at 0 → because memory & math love it
✅ Slicing = Powerful Tool → extract parts of a sequence
✅ Copying → know shallow vs deep copy
✅ Custom Sequences → implement __getitem__
and __len__
Mastering sequences will make you a better Python (and general) programmer you’ll think about memory, efficiency, and data structure design like a pro.
Top comments (0)