why no ++?

Markus Schaber markus at schabi.de
Sun Aug 12 06:16:49 EDT 2001


Hi,

Stefan Schwarzer <s.schwarzer at ndh.net> schrub:

>> I'm not sure what you mean, since 'lvalue' is not a Python
>> concept, but...:
>> 
>>     a=b,c,d=e='wow'
> 
> Nice, but seems like "obfuscated Python" to me ;-)

Well - you can obfuscate in any language. But - and this is the big 
plus - Python doesn't _force_ you to do it :-)

 
>>>> a,b,c,d,e
> ('wow', 'w', 'o', 'w', 'wow')
> 
> I haven't yet figured out how it works. Could you please add
> parantheses to the above expression or clarify otherwise how it works?

'wow' is a string.

This string as a whole is assigned to e.

Then - as the string is a sequence of length 3 - Python does 
"Tupel-Unpacking" to b,c,d which assigns one char to each.
(try b,c,d='wowo' and you get 'ValueError: unpack sequence of wrong 
size'.)

Remember that a tupel doesn't need brackets around it in certain 
situations.

And - last but not least - the string is assigned to a. But there's the 
original String assigned to a, try the following:

>>> b,c,d='wow'
>>> a = b,c,d
>>> print a
('w', 'o', 'w')

This way a is a tupel of the three chars (=strings with length 1), not 
a string with length 3.

For further confusion, typing a,b,c,d,e on the command prompt
>>> a,b,c,d,e
('wow', 'w', 'o', 'w', 'wow')
implicitely builds a tupel of those 5 values - as an expression can 
have only one value which is the tupel in this case, thats why there 
are brackets around it.

The print command itsself has a "higher priority" to eat the commas for 
separation of parameters, so you need the brackets if you want a tupel.

>>> print a,b,c,d,e
wow w o w wow
>>> print (a,b,c,d,e)
('wow', 'w', 'o', 'w', 'wow')

Powerful, but can be confusing. Happily, the most cases just give the 
result you would expect instinctively - sign of a good language design.

markus
-- 
1) Customers cause problems.
2) Marketing is trying to create more customers.
Therefore:
3) Marketing is evil.  (Grand Edwards in comp.lang.python)



More information about the Python-list mailing list