Search code examples
pythonlistvariablesautomatic-ref-counting

How to create automatic variables for large number of values in list. For ex. list with 50 values how can we assign values to 50 different variables


How can we assign large number of different variables to large number of list values for example. x1, x2, x3 upto xn.


Solution

  • You can use exec which evaluates a string at runtime and then executes it as you were typing it. Combine it with the format specifier and the string concatenations and you have>

    s = ""
    for i in range(0,10):
        s+="x{0} = mylist[{0}]\n".format(i)
    
    mylist = [i*i for i in range(10)]
    exec(s)
    

    which is equivalent to typing manually:

    x0 = mylist[0]
    x1 = mylist[1]
    x2 = mylist[2]
    x3 = mylist[3]
    x4 = mylist[4]
    x5 = mylist[5]
    x6 = mylist[6]
    x7 = mylist[7]
    x8 = mylist[8]
    x9 = mylist[9]
    

    You can then test it this way:

    p = ""
    for i in range(10):
        p+="print(\"x{0} = \",x{0})\n".format(i)
    exec(p)       
    

    Which gives you:

    x0 =  0
    x1 =  1
    x2 =  4
    x3 =  9
    x4 =  16
    x5 =  25
    x6 =  36
    x7 =  49
    x8 =  64
    x9 =  81
    

    However, quoting this answer

    the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.