4 ms·
Interesting. It seems that (according to my Python prompt) x, y = 1, 2 and [x, y] = 1, 2 and even x, y = [1, 2] are all identical in function. Are t
by qwph 18y ago
Interesting. It seems that (according to my Python prompt)
x, y = 1, 2
and
[x, y] = 1, 2
and even
x, y = [1, 2]
are all identical in function. Are there any (subtle) distinctions between the three?
- DaniFong 18y agoI don't know if there are any higher level differences, but I suspect the pure tuple version (the first) would be a little faster. Edit: Nope! Up to randomness due to multitasking and paging, a benchmark on one million cases yields the same times, up to noise.
- scott_s 18y agoThe last is different in that it returns a list, not a tuple. This makes a difference if you want to change the object. >>> tuple = x, y = 1, 2 >>> type(tuple) <type 'tuple'> >>> tuple (1, 2) >>> tuple[0] = 1 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object doesn't support item assignment >>> lst = x, y = [1, 2] >>> type(lst) <type 'list'> >>> lst [1, 2] >>> lst[0] = 3 >>> lst [3, 2]
- qwph 18y agoAha! There's actually no difference (i think) between: 1, 2 and: (1, 2) That seems to make sense.
- scott_s 18y agoI think that is true, but I think that it's only later versions of Python (2.5+, maybe?) that allow you to omit the parenthesis. I've had earlier versions (2.3?) complain of a syntax error when I leave them out.