Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Python 2.7, why do I have to enclose an `int` in brackets when I want to call a method on it?

Tags:

python

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
like image 773
BioGeek Avatar asked Nov 22 '13 08:11

BioGeek


People also ask

What are [] used for in Python?

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.

What is the difference between () and [] in Python?

() 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 does {} brackets mean in Python?

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.

Why is Python printing with parentheses?

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.


2 Answers

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.

like image 112
Thomas Orozco Avatar answered Oct 20 '22 00:10

Thomas Orozco


Because 5.something would be parsed as a floating point number.

like image 25
Wolph Avatar answered Oct 19 '22 23:10

Wolph