Using the slicing method [start:] we can easily skip the first index 0 and start a for-loop at index 1 in Python. It will skip the first element in the loop.
In Python, by default, the index of a for loop starts at 0. However, if you want to start the index at 1, you can use the built-in enumerate()
function to add an offset of 1 to the index.
Python for loop index starts at 1 example
A simple example code starting a for loop at the index 1
skips the first index 0
. Element b will not print because its index value is 0.
a_list = ["a", "b", "c"]
for item in a_list[1:]:
print(item)
Output:
Python for loop starts at index with enumerate
If you want to start from 1 instead of 0. This method will not skip the first content just starting indexing at 1.
items = ["a", "b", "c"]
for count, item in enumerate(items, start=1):
print(count, item)
Output:
1 a
2 b
3 c
Another example
my_list = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(my_list, start=1):
print(f"{i}. {fruit}")
Comment if you have any doubts or suggestions on this Python for loop topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.