'What do backticks mean to the Python interpreter? Example: `num`
I'm playing around with list comprehensions and I came across this little snippet on another site:
return ''.join([`num` for num in xrange(loop_count)])
I spent a few minutes trying to replicate the function (by typing) before realising the `num` bit was breaking it.
What does enclosing a statement in those characters do? From what I can see it is the equivalent of str(num). But when I timed it:
return ''.join([str(num) for num in xrange(10000000)])
It takes 4.09 seconds whereas:
return ''.join([`num` for num in xrange(10000000)])
takes 2.43 seconds.
Both give identical results, but one is a lot slower. What is going on here?
Oddly... repr() gives slightly slower results than `num`. 2.99 seconds vs 2.43 seconds. I am using Python 2.6 (haven't tried 3.0 yet).
Solution 1:[1]
Backtick quoting is generally non-useful and is gone in Python 3.
For what it's worth, this:
''.join(map(repr, xrange(10000000)))
is marginally faster than the backtick version for me. But worrying about this is probably a premature optimisation.
Solution 2:[2]
My guess is that num doesn't define the method __str__(), so str() has to do a second lookup for __repr__.
The backticks look directly for __repr__. If that's true, then using repr() instead of the backticks should give you the same results.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mortensen |
| Solution 2 | Aaron Digulla |
