In Python, are expressions like 10**9 made of literals also literals? What I am asking: is there a cost to using expressions over less-meaningful but also less-computable literals in code that is called very often and should be lightweight?

4 Answers
4

It's more about readability and coding style. By writing something like 10**9 instead of 1000000000 or etc., you'll make your code shorter and more readable, thus its maintenance and improvement would be easier. If you want to use 10**9 multiple times in your code, as a more elegant way you'd better use it as a global variable at the top level of your module which is more elegant. Like:

MY_VARIABLE = 10**9

Note that even if you don't use a global variable name and use its numerical value through your code python will assume it's a constant value and won't recalculate it every time.

For example, as you can see in the following bytecode, python will load the constant value (which you defined in first part for a) for c and doesn't create a new object 1 for that:

There is a cost to using expressions, namely a performance cost due to Python precomputing constant expressions, but this cost is not likely to be noticeable in most cases, like in the case of 10**9, more so with cases like 10**(10**10).