Search code examples
pythonfor-loopdesign-principles

Reuse same variable name twice within a for loop


for i in rates:
    if input_currency == currency:
        if output_currency in rates[currency]:
            pass 
        else:
            for i in rates:

Is it generally a bad thing to use the same variable i again within a for loop? Even if I loop through the same data structure again? PyCharm just tells me it's been used already, but it still works.


Solution

  • It's not wrong. But it's dangerous if you don't know what you are doing. For example, you might have problems if you want to use i inside the outer loop:

    rates = [1,2,3,4,5]
    for i in rates:
        for i in rates:
            pass
        print(i) # This always prints 5
    

    This may confuse you if you're not familiar with Python. In C, for example, a variable defined inside the inner loop is different from the one that is defined in the outer loop (i.e., you can reuse the same name for different variables).