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
mystack
  • 4,910
  • 10
  • 44
  • 75

2 Answers2

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))
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
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
Community
  • 1
  • 1
sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • 1
    **If** you use a loop, use a generator expression and avoid creating a list object. – Martijn Pieters Apr 22 '14 at 11:32
  • @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. – user2357112 Apr 22 '14 at 11:35
  • Just replace the `[..]` square brackets with `(..)` parenthesis, see my answer. – Martijn Pieters Apr 22 '14 at 11:35
  • @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. – Martijn Pieters Apr 22 '14 at 11:36
  • @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. – user2357112 Apr 22 '14 at 11:41
  • @user2357112: In Python 3, both generator expressions and list comprehensions use a separate scope (call frame). The code object is a constant, in any case, the list object isn't. – Martijn Pieters Apr 22 '14 at 11:43
  • @MartijnPieters: In a quick [test](http://ideone.com/Th8OGs) with Python 3, the list version still runs faster than the generator version, though not by as much as in Python 2. I really don't think this is a case where we should care about list vs. generator. – user2357112 Apr 22 '14 at 11:50
  • @user2357112: sure, as I said, it *may* run faster, depending on what is done in the loop. This is not a case where I'd use a loop *at all*, as for just 3 items, the assignment is optimized not to use a tuple at all. – Martijn Pieters Apr 22 '14 at 11:51