0

I have python variables as given below.

global a,b,c

i want to initialize all these variables with different values in a single statement.

is it possible?

a=b=c=uuid.uuid1() //should return different values for a,b and c

2 Answers 2

5

Call uuid.uuid1() three times:

a, b, c = uuid.uuid1(), uuid.uuid1(), uuid.uuid1()

You could make that a loop, but for 3 fixed items, why bother? Moreover, for an unpacking assignment like this with just 2 or 3 elements, the CPython compiler optimizes the bytecode.

If you use a loop anyway (if you have a few more targets to assign to), use a generator expression and avoid creating a list object:

a, b, c, d, e, f, g, h = (uuid.uuid1() for _ in xrange(8))
Sign up to request clarification or add additional context in comments.

Comments

1

You can do that using a generator as:

a,b,c = (uuid.uuid1() for _ in range(3))

It will be particularly useful when you have lots of variables to assign data to.

Example

a,b,c = (randint(1,10) for _ in range(3))

>>> print a,b,c
7 2 9

8 Comments

If you use a loop, use a generator expression and avoid creating a list object.
@MartijnPieters: Why bother? It's 3 items, and it's not like we can avoid having them all in memory at once (since they're immediately assigned to a, b, and c). I think the generator object might actually be bigger than the list.
Just replace the [..] square brackets with (..) parenthesis, see my answer.
@user2357112: It can never be 'bigger'; it could be slower to process, except that the exact same bytecode is executed. But minus creating a list object.
@MartijnPieters: Bigger due to overhead like the frame object, which appears to be 432 bytes on my machine. Avoiding the creation of a 3-element list object doesn't seem worthwhile here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.