Why don't we have to initialize the variable of a for loop?


#1

Question

In Python, why don’t we have to initialize the variable of a for loop?

Answer

In Python, a for loop variable does not have to be initialized beforehand.

This is because of how Python for loops work. When it runs, the for loop statement will initialize the variable to the first character of the string, and continue updating its value to the subsequent characters in the string, until the loop reaches the final character or is terminated before that.

Example

# This initialization is not necessary!
i = 0

# i is initialized to the first character, "1"
for i in "12345":
  print(i)

# The output will be
# 1 
# 2
# 3
# 4
# 5