[Tutor] Java style assignments in Python

Jeff Shannon jeff at ccvcorp.com
Wed Sep 10 11:50:05 EDT 2003


tpc at csua.berkeley.edu wrote:
> hello all, I was curious if there is a way to implement Java style
> assignments in Python.  Let's say I have a block of code:
> 
> list_A = []
> list_B = []
> list_C = []
> 
> and I want to condense it to:
> 
> list_A, list_B, list_C = []
> 
> Is there any way to do this without generating an error:
> 
> ValueError: unpack list of wrong size
> 
> ?  Thanks in advance

No, because the "condensed" version means something different in Python.

 >>> foo = [1, 2, 3]
 >>> a, b, c = foo
 >>> a
1
 >>> b
2
 >>> c
3
 >>>

The line in question actually constructs a temporary tuple with the 
(previously unassigned) names, and then assigns foo to that tuple. 
This is called tuple (or list) unpacking, which should explain the 
wording of the error message you're getting.

You can do something that's somewhat similar, however --

 >>> a = b = c = 1
 >>> a
1
 >>> b
1
 >>> c
1
 >>>

Chaining assignments like this will achieve almost the effect you 
want... but you'll find an interesting twist when using it with lists 
(or other mutable objects).

 >>> a = b = c = []
 >>> b
[]
 >>> a.append(1)
 >>> b
[1]
 >>> c
[1]
 >>>

The problem here is that a, b, and c all point to the *same* list 
object.  Since there's only one underlying object, changes to one will 
seem to affect all three.  You need to explicitly create a separate 
empty list for each one in order to have properly independent 
behavior.  (You may want to search the archives of this list or 
comp.lang.python for "name rebinding" for detailed explanations of how 
all of this works.)

However, combining all of this, we can still do it in a single line --

 >>> a, b, c = [], [], []
 >>> b.append(23)
 >>> a
[]
 >>> b
[23]
 >>> c
[]
 >>>

Hope this helps...

Jeff Shannon
Technician/Programmer
Credit International




More information about the Tutor mailing list