Home>

When using for in python

a = 1
b = 2
c = 3
If I want to put a different value in another variable like

for i in range (3):
    a = i


This code overwrites a and cannot be entered.
I want to change the name of a variable for each loop in the for statement and put a value in a different variable.
Is there any good way to write it?

It's a story that you only have to write one by one, but it looks dirty
It is difficult to write when the number increases, so please let me know if there is a good way to write it.

  • Answer # 1

    I don't think I can recommend it very much,
    Dynamically define variables in python

    Is it helpful? I think it's better to do something with an array normally.

    Well, if you try to do it, it will be like this ...

    for i in range (3):
        exec ("a {} = {}". format (i, i))
        exec ("{} = {}". format (chr (i + ord ("a")), i))
    print (a0, a1, a2)
    print (a, b, c)

  • Answer # 2

    exec ()How about using a function?

    for i in range (3):
        exec ("variable% d =% d"% (i, i))
    print (variable0) # 0
    print (variable1) # 1
    print (variable2) # 2