How to start a for loop at 1 - Python
Last Updated :
02 Dec, 2024
Python for loops range typically starts at 0. However, there are cases where starting the loop at 1 is more intuitive or necessary such as when dealing with 1-based indexing in mathematics or user-facing applications.
Let's see some methods to start a for loop at 1 in Python.
Using range() with a Start Parameter
range() function allows us to specify a start, stop, and step. By default, it starts at 0 but we can specify 1 as the starting point.
Python
# Loop starting at 1
for i in range(1, 6): # Loop from 1 to 5
print("Current number:", i)
The range(1, 6) specifies a start of 1 and goes up to 5 (excluding 6 as range is non-inclusive), this is the simplest and most common way to start a loop at 1.
Let's explore some other methods to start a for loop at 1.
Using a List or Sequence Starting at 1
If we have a predefined sequence such as a list starting at 1 then we can iterate directly over it.
Python
# Predefined list
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print("Current number:", num)
In this example, the list numbers starts at 1 so the loop iterates directly over the elements without needing range.
Using Enumerated Loop Starting at 1
If we are iterating over a collection but need an index that starts at 1 the enumerate() function is useful. It has an optional start parameter to specify the starting index.
Python
# List of items
items = ["apple", "banana", "cherry"]
for idx, item in enumerate(items, start=1):
print(f"Item {idx}: {item}")
enumerate(items, start=1) provides an index starting at 1 while iterating over the list.
Manually Incrementing a Variable
In scenarios where a loop inherently starts at 0 we can initialize a counter variable at 1 and increment it manually.
Python
# Initialize counter
start = 1
for _ in range(5): # Loop 5 times
print("Current number:", start)
start += 1
The start variable begins at 1 and is manually incremented in each iteration