in Python 2.7, why do I have to enclose an int
in brackets when I want to call a method on it?
>>> 5.bit_length()
SyntaxError: invalid syntax
>>> (5).bit_length()
3
Index brackets ([]) have many uses in Python. First, they are used to define "list literals," allowing you to declare a list and its contents in your program. Index brackets are also used to write expressions that evaluate to a single item within a list, or a single character in a string.
() is a tuple: An immutable collection of values, usually (but not necessarily) of different types. [] is a list: A mutable collection of values, usually (but not necessarily) of the same type.
What do {} bracket mean in Python? [] brackets are used for lists. List contents can be changed, unlike tuple content. {} are used to define a dictionary in a “list” called a literal.
In Python 2.7, which you're using, the parens (and the comma separator) are actually creating a tuple and its that tuple that's being printed out.
That's a parser idiosyncrasy.
When Python sees the .
, it starts looking for decimals. Your decimal is a b
, so that fails.
If you do (5).bit_length()
, then Python will first parse what's between the ()
, and then look for the bit_length
method.
If you try:
5..zzz
You'll get the AttributeError
you expect. This won't work for integers though: 5.
is a float.
Because 5.something
would be parsed as a floating point number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With