Home > front end >  What does "i" in "for i in range ()" mean?
What does "i" in "for i in range ()" mean?

Time:06-08

I understand what "for" and "range" do in for-loops, but can't get what exactly "i" does in them. Can you explain?

CodePudding user response:

i is a variable that is an iterable used in the for-loop (in this case, range(x))

i can be changed out with any other character or word, i recommend you used i as your standard practice or something which relates to what you are looping.

range(x) can also be changed out for any iterable. For example:

names = ['janet', ' bob', 'charlie']
for name in names:
    print(name)

# Output: janet bob charlie

More examples of for-loops:

grid = [[0, 1, 2], 
        [3, 4, 5], 
        [6, 7, 8]]

for row in grid:
    print(row)

# Outputs:
# [0, 1, 2]
# [3, 4, 5]
# [6, 7, 8]

for row in range(3):
    for col in range(3):
        print(grid[col][row])

# Outputs: 0 3 6 1 4 7 2 5 8
# Prints a single digit at a time going from the first of each array to the last
# Instead of printing out an array at a time
  • Related