Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use "i" in loops such as in "for i in range"?

Why is "i" often used in learning materials when illustrating loops?

For example, it's used when looping over a range function. Using a random number just seems more logical to me since the range function is dealing with numbers.

like image 407
CrunchingMyBrain Avatar asked Dec 06 '25 14:12

CrunchingMyBrain


1 Answers

Asking why we use i is kind of like asking why so many people use the letter x in math problems. It is mostly because i is just a very easy variable to use to represent the current increment in a loop.

I also think you are confused about the place of i in a loop. When you use a range loop you are saying that you want to count one by one from one number until you hit another. Typically it would look like this

for i in range(0, 5):

This means I want to count from 0-4 and set i to the current loop I am currently on.

A great way to test this.

for i in range(0, 5):
  print("i currently equals: ", i)

The result will be

i currently equals: 0
i currently equals: 1
i currently equals: 2
i currently equals: 3
i currently equals: 4

In your question you ask why don't you set i to a number and it is because you can not use numbers as variable names. Python cannot accept what you are asking, but if it could it would look like this

for 54 in range(0, 5):
  print(54)

Try reading up a little more on what variables are and how to properly use them in programming: https://en.wikibooks.org/wiki/Think_Python/Variables,_expressions_and_statements

like image 137
wezley Avatar answered Dec 08 '25 03:12

wezley