2
print(type(1))
print(type((1)))

gives me

<class 'int'>

Also

print(id(1))
print(id((1)))

gives me

1555424112
1555424112

however (1) is recognized as an instance where as 1 is not? for e.g., on doing a (1). in editor I get a lot of methods such as bit_length, conjugate, __add__() etc. but not in doing 1.

What is the reason for the distinction?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
QVSJ
  • 1,165
  • 2
  • 12
  • 22

3 Answers3

13

(..) merely groups an expression. For integers, it also has the side-effect that the . character for floating point decimals can be disambiguated from the . attribute access operator.

So

1.bit_length()

is a syntax error, because bit_length is not a valid non-integer portion for a real number. But

(1).bit_length()

is valid Python syntax, because now the parser won't see the . token as part of the number literal.

Alternatively, add a space:

1 .bit_length()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

n and (n) are the same expression.

But watch out for this (n,) that is a tuple of one element.

id() is not the way to compare expressions. It tells you if you objects are the same object. And Python treats small number specially so that id() is always the same in any python session.

So you get this behaviour:

The id() is the same as id(1) for is(1+1-1)

>>> id(1),id(1+1-1)
(140246128484064, 140246128484064)

But for larger numbers the id() changes.

>>> id(3000000),id(3000000+1-1)
(140246130143120, 140246129522640)

Use == for expression comparison.

Barry Scott
  • 799
  • 6
  • 13
-2

To print it, you would just do Print(n1-n2)