0
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.

1

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

7 Comments

how about using a generator so the list is not actually builded? a, b, c = ([0 for i in xrange(a*b*c)] for _ in xrange(3))
@DanielSanchez - We could do that, certainly. However, seeing any performance benefit from it would require creating many more lists than should be unpacked into multiple independent variables in a single line. It only has to store the references anyway, which are small.
please can you explain a bit further, as I see it you are building the a list wich contains another lists, but you will never use that list. By using a generator you just get rid of that list. Am I wrong or missing something? thanks!!
@DanielSanchez - It would get rid of a list, yes, but the list is tiny, and it should never be anything but tiny.
you meaned that, ok, either way I think it should not be used, just think it is in a loop of 1000 iterations, you will be creating 1000 lists, must take care of that. Thanks for the explanation, good answer.
|
1

Looking at your stated intention rather than at the 'one line' requirement:

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

Not sure the optimizer is clever enough to avoid repeated multiplication at:

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

Suppose a, b, and c were properties, so reading them would have side effects. How could the optimizer know this in a dynamically typed language?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.