When you call range() with two arguments, the first argument is the starting number, and the second argument is the end (non-inclusive). So you're starting from len(list_of_numbers), which is 5, and you're ending at 6. So it just prints 5.

To get the results you want, the starting number should be 0, and the end should be len(list_of_numbers)+1. If you call it with one argument, that's the end, and 0 is the default start. So use

for i in range(len(list_of_numbers)+1):

or if you want to pass the start explicitly:

for i in range(0, len(list_of_numbers)+1):
Answer from Barmar on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ gloss_python_for_range.asp
Python Looping Through a Range
The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3): ... Python For Loops Tutorial For Loop Through a String For Break For Continue ...
Discussions

Understanding Range() function in python. [Level: Absolute Beginner]
You can think of range as returning a sequence of numbers. Since we use the syntax for in : to loop or iterate over a sequence, naturally we can put a range as the sequence. Does that help? More on reddit.com
๐ŸŒ r/learnpython
23
4
August 6, 2024
"for i in range()" to do an infinite loop with a counter - Ideas - Discussions on Python.org
Hi, Usually in Python we can avoid ... enumerate(...), for i in range(100), etc. Along the years I have nearly always found a more โ€œpythonicโ€ replacement for code containing i = 0 โ€ฆ i += 1. There is an exception with this code: an infinite loop with a counter: i = 0 while ... More on discuss.python.org
๐ŸŒ discuss.python.org
4
August 10, 2022
Is there a way to change the value of range in a for loop?
It's hard to give feedback if you don't tell us what you want to do. More on reddit.com
๐ŸŒ r/learnpython
26
10
June 20, 2023
language design - What is the reason python uses range in for loops? - Software Engineering Stack Exchange
Note that range() is not actually part of the python language; it is a function. Having range be a function means you can plug any other function into a "for in" loop, including functions that don't increase monotonically, functions that lazy-execute, and functions that replace range() with ... More on softwareengineering.stackexchange.com
๐ŸŒ softwareengineering.stackexchange.com
November 8, 2019
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-loop-through-a-range
Python - Loop Through a Range - GeeksforGeeks
July 23, 2025 - The most simple way to loop through a range in Python is by using the range() function in a for loop.
๐ŸŒ
Snakify
snakify.org โ€บ for loop with range
For loop with range - Learn Python 3 - Snakify
Such a sequence of integer can be created using the function range(min_value, max_value): ... Function range(min_value, max_value) generates a sequence with numbers min_value, min_value + 1, ..., max_value - 1.
๐ŸŒ
StrataScratch
stratascratch.com โ€บ blog โ€บ python-for-loop-range-function
How Does Python For Loop Range Function Work? - StrataScratch
November 5, 2025 - Loop starts: Python asks range(1, 6) for the first number โ†’ gets 1 ... We will solve three different challenges by using for loops and range together. Letโ€™s start with the mathematical challenge. Task: The task is to find all numbers between 1 and 100 that are divisible by both 3 and 5. ...
Find elsewhere
๐ŸŒ
Python.org
discuss.python.org โ€บ ideas
"for i in range()" to do an infinite loop with a counter - Ideas - Discussions on Python.org
August 10, 2022 - Hi, Usually in Python we can avoid the i = 0 โ€ฆ i += 1 paradigm that we use in other languages when we need to count things, thanks to enumerate(...), for i in range(100), etc. Along the years I have nearly always found a more โ€œpythonicโ€ replacement for code containing i = 0 โ€ฆ i += 1. There is an exception with this code: an infinite loop with a counter: i = 0 while True: ... if breaking_condition: break i += 1 Proposal: could we accept that range() without any parameter ...
๐ŸŒ
Codecademy
codecademy.com โ€บ forum_questions โ€บ 522215b7f10c60e27d0017de
Why should we use range in for loops? | Codecademy
n = [3, 5, 7] def total(List): total_sum = 0 for item in range(len(List)): total_sum += List[item] return total_sum print total(n)
๐ŸŒ
Indiachinainstitute
indiachinainstitute.org โ€บ wp-content โ€บ uploads โ€บ 2018 โ€บ 05 โ€บ Python-Crash-Course.pdf pdf
Python crash course
Doing More Work Within a for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 ยท Doing Something After a for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 ... Avoiding Indentation Errors . . . . . . . . . . . . . . .
๐ŸŒ
TryHackMe
tryhackme.com โ€บ room โ€บ pythonsimpledemo
Python: Simple Demo
3 weeks ago - You need to enable JavaScript to run this app
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_func_range.asp
Python range() Function
Python Examples Python Compiler ... Training ... The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number....
๐ŸŒ
Real Python
realpython.com โ€บ python-range
Python range(): Represent Numerical Ranges โ€“ Real Python
November 24, 2024 - In Python, the range() function generates a sequence of numbers, often used in loops for iteration. By default, it creates numbers starting from 0 up to but not including a specified stop value. You can also reverse the sequence with reversed().
Top answer
1 of 2
8

Note that range() is not actually part of the python language; it is a function. Having range be a function means you can plug any other function into a "for in" loop, including functions that don't increase monotonically, functions that lazy-execute, and functions that replace range() with something that better satisfies your personal sensibilities.

In other words, python's way affords you tremendous flexibility to do it however you want.

Your example is not exactly a fair one. It describes a scenario that would be very rare in practice. For a dice roll, it is simply

 for x in range(6)
2 of 2
6

There are multiple different ways to approach this answer (bold emphasis mine):

What is the reason python uses range in for loops?

This is not a for loop. It is a foreach loop. I.e. it is not a loop that loops over a pre-defined set of loop indices, it is an iterator that iterates over the elements of a collection.

In particular, in

for e in [2, 3, 5, 7, 11, 13, 17]:
    print(e)

The result will not be

0
1
2
3
4
5
6

but

2
3
5
7
11
13
17

What is the reason python uses range in for loops?

It doesn't. It uses an arbitrary expression. More precisely, an arbitrary expression that evaluates to an iterator or to something that can be implicitly converted to an iterator (such as an iterable):

class MyIterator:
    def __init__(self):
        self.counter = -1
        self.lost = [4, 8, 15, 16, 23, 42]

    def __next__(self):
        self.counter += 1

        if self.counter == 6:
            raise StopIteration

        return self.lost[self.counter]

class MyIterable:
    def __iter__(self):
        return MyIterator()

my_iterable = MyIterable()

for num in my_iterable:
    print(num)

# 4
# 8
# 15
# 16
# 23
# 42

Is there some philosophical reasoning behind why python uses this syntax

Yes: It is more general and thus makes the language simpler. The BASIC for loop can do one thing and one thing only: loop over a pre-defined set of loop indices. In fact, it is even more limited than that, because there are further restrictions on the loop indices: they need to be monotonically increasing or decreasing with a fixed step size.

If you want the indices to be non-monotonic, you need a new language construct. If you want the indices to have varying step sizes, you need a new language construct. If you want to iterate over the elements of a collection, you need a new language construct.

With Python's foreach loop, you can simply have a function that generates indices in whatever order you want, and loop over those. You can iterate over the elements of any arbitrary collection, and note that "collection" is interpreted very broadly.

Actually, you can iterate over the elements of any arbitrary iterator. An iterator can be something very general, and it doesn't even have to be finite, e.g. "all prime numbers".

As I have shown above, it is very easy to create your own custom iterators and iterables. It is in fact even more easy using generator functions:

def my_generator():
    yield 4
    yield 8
    yield 15
    yield 16
    yield 23
    yield 42

for num in my_generator():
    print(num)

# 4
# 8
# 15
# 16
# 23
# 42

And even more easy with generator expressions.

If Python is supposed to be more human readable than most languages, in this case particular case it seems to be worse than say Sinclair BASIC.

If you are looping over loop indices in Python (or any modern language, really), you are doing it wrong.

You should be using higher-level iterators instead, such as reduce (you may also know this one under the name fold or more general Catamorphism), accumulate (you may also know this one under the name scan or prefix-sum), cycle, chain, groupby, or product. Or, you should be using list / set / dictionary comprehensions, generator expressions, or algorithms and data structures supplied by the standard library or third-party libraries.

๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-for-loop-for-i-in-range-example
Python For Loop - For i in Range Example
March 30, 2021 - # Example with three arguments for i in range(-1, 5, 2): print(i, end=", ") # prints: -1, 1, 3, In this article, we looked at for loops in Python and the range() function.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ range-function
Python range() Function [Python Tutorial]
The range() function generates a sequence of numbers, which is most commonly used to control for loops. It can be called in three ways: ... Become a Python developer. Master Python from basics to advanced topics, including data structures, functions, classes, and error handling ...
๐ŸŒ
Andrej Karpathy
karpathy.github.io โ€บ 2026 โ€บ 02 โ€บ 12 โ€บ microgpt
microgpt
February 12, 2026 - The parameters are frozen and we just run the forward pass in a loop, feeding each generated token back as the next input: temperature = 0.5 # in (0, 1], control the "creativity" of generated text, low to high print("\n--- inference (new, hallucinated names) ---") for sample_idx in range(20): keys, values = [[] for _ in range(n_layer)], [[] for _ in range(n_layer)] token_id = BOS sample = [] for pos_id in range(block_size): logits = gpt(token_id, pos_id, keys, values) probs = softmax([l / temperature for l in logits]) token_id = random.choices(range(vocab_size), weights=[p.data for p in probs])[0] if token_id == BOS: break sample.append(uchars[token_id]) print(f"sample {sample_idx+1:2d}: {''.join(sample)}")
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-range-function-example
Python range() Function Example
March 17, 2023 - For that, you could use range() and pass the length of your list as an argument to the function. To calculate the length of a list, use the len() function. programming_languages = ["Python", "JavaScript", "Java", "C++"] programming_languages_length ...
๐ŸŒ
PyTorch
docs.pytorch.org โ€บ intro โ€บ learn the basics โ€บ datasets & dataloaders
Datasets & DataLoaders โ€” PyTorch Tutorials 2.11.0+cu130 documentation
July 20, 2022 - labels_map = { 0: "T-Shirt", 1: "Trouser", 2: "Pullover", 3: "Dress", 4: "Coat", 5: "Sandal", 6: "Shirt", 7: "Sneaker", 8: "Bag", 9: "Ankle Boot", } figure = plt.figure(figsize=(8, 8)) cols, rows = 3, 3 for i in range(1, cols * rows + 1): sample_idx = torch.randint(len(training_data), size=(1,)).item() img, label = training_data[sample_idx] figure.add_subplot(rows, cols, i) plt.title(labels_map[label]) plt.axis("off") plt.imshow(img.squeeze(), cmap="gray") plt.show()
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_for_loops.asp
Python For Loops
The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3): ... Note: The else block will NOT be executed if the loop is stopped by a break ...