› Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 6: Python › MITx 6.100L Introduction to CS and Programming Using Python › Why Does Bubble Sort Use range(1, len(L)) Instead of Starting at 0?
- This topic is empty.
-
AuthorPosts
-
April 29, 2026 at 8:15 am #6483
When beginners learn Python loops, one common question appears:
for j in range(1, len(L)):Why does this start at
1?Isn’t Python like C, where indexing starts at
0?Short Answer
Yes — Python lists are zero-indexed, just like C arrays.
But Bubble Sort starts this loop at
1because the algorithm compares:L[j - 1] and L[j]Starting at
1ensures the first comparison is:L[0] and L[1]which is correct.
Python Lists Still Start at 0
Example:
L = [8, 4, 1, 6]Indexes:
0 → 8 1 → 4 2 → 1 3 → 6So Python definitely uses zero-based indexing.
Why Not Start at 0?
The Bubble Sort code uses:
if L[j - 1] > L[j]:If the loop started with:
j = 0Then Python would calculate:
L[j - 1] = L[-1]And in Python:
L[-1]means the last element of the list.
So Python would compare:
last item vs first itemThat is incorrect for Bubble Sort.
Why Starting at 1 Works
First loop value:
j = 1Then:
L[j - 1] = L[0] L[j] = L[1]So first comparison becomes:
first item vs second itemPerfect.
Next:
j = 2 → compare L[1] and L[2] j = 3 → compare L[2] and L[3]Exactly what Bubble Sort needs.
Even in C, This Is Common
In C, if comparing:
arr[j - 1] > arr[j]Many programmers also start:
for (j = 1; j < n; j++)So this is not a Python-only thing.
Alternative Python Version Starting at 0
You can rewrite Bubble Sort like this:
for j in range(0, len(L) - 1): if L[j] > L[j + 1]: swap...Now comparisons become:
L[0] vs L[1] L[1] vs L[2] L[2] vs L[3]Also correct.
Mental Model
If code compares:
L[j - 1] and L[j]Start loop at:
1If code compares:
L[j] and L[j + 1]Start loop at:
0
One-Line Takeaway
Python lists start at 0, but Bubble Sort uses
range(1, len(L))soL[j-1]safely points to the previous item. -
AuthorPosts
- You must be logged in to reply to this topic.
