Search code examples
pythoninitializationgenerator-expression

Initialize multiple lists in python


a = 2
b = 3
c = 4
x = y = z = [0 for i in xrange(a*b*c)]

Is there a way in which x,y,z can be initialized in one line (because I don't want to multiply a, b and c for each list initialization), as separate lists of 0s. In the above if x is updated, then y and z are also get updated simultaneously with the same changes.


Solution

  • Just use another comprehension and unpack it:

    x, y, z = [[0 for i in xrange(a*b*c)] for _ in xrange(3)]
    

    Note that [0 for i in xrange(a*b*c)] is equivalent to the simpler [0] * a*b*c.