3 ms·
Very good idea, I support this and will use it from now on (even though I don't like the (thing,) Python syntax very much), as it's the only way to say that the
by StavrosK 16y ago
Very good idea, I support this and will use it from now on (even though I don't like the (thing,) Python syntax very much), as it's the only way to say that the iterable should only have one element.
- tkeller 16y agoAs a commenter there noted, [thing] = stuff works too. I think I like that even better.
- StavrosK 16y agoOh, you're very much correct. Let me benchmark that... There doesn't appear to be any difference in speed between the two. Assigning the result to one variable (totally different to this) is about 6% faster, so this syntax is what I'll use, thank you!
- jrockway 16y agoAssigning the result to one variable (totally different to this) is about 6% faster, so this syntax is what I'll use, thank you! On your exact machine with your exact version of Python, today. Please don't let microbenchmarks dictate what code you write. If you need a 6% performance gain in a microbenchmark, you've chosen the wrong language to use. Python is about readability and maintainability, not syntax hacks to make some benchmark slightly faster.
- StavrosK 16y agoThe point of the above post was to say "this is nice syntax, and it isn't ten times slower, so it's good on that front too", not to say "use that because it's 6% faster". I'm never going to write this in a tight loop anyway, and even if I did, I'd benchmark the entire piece of code, not just this line.
- mikeklaas 16y agoThe brackets are optional; you can also write thing, = [stuff] though some people think that it's less legible since it has a completely different meaning without the comma. EDIT: you can even play with the whitespace and pretend that ",=" is a list->scalar conversion operator: x ,= [1]
- StavrosK 16y agoI know about the optional parentheses, but omitting them makes the comma very easy to overlook :/ I do like your fake operator idea, but it seems that it would go against the spirit of python and make it easier at the expense of readability...