I come from a Javascript background (where properties can be accessed through both .
and []
notation), so please forgive me, but what, exactly, is the difference between the two in Python?
From my experimentation it seeems that []
should always be used, both to get the index of a list
or set
and to get the value from a certain key in a dictionary
. Is this correct, and, if not, when do you use a .
in Python?
Dot notation indicates that you're accessing data or behaviors for a particular object type. When you use dot notation, you indicate to Python that you want to either run a particular operation on, or to access a particular property of, an object type.
Key DifferencesDot notation is faster to write and easier to read than bracket notation. However, you can use variables with bracket notation, but not with dot notation. This is especially useful for situations when you want to access a property but don't know the name of the property ahead of time.
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.
The indexing operator (Python uses square brackets to enclose the index) selects a single character from a string. The characters are accessed by their position or index value. For example, in the string shown below, the 14 characters are indexed left to right from postion 0 to position 13.
The dot operator is used for accessing attributes of any object. For example, a complex number
>>> c = 3+4j
has (among others) the two attributes real
and imag
:
>>> c.real 3.0 >>> c.imag 4.0
As well as those, it has a method, conjugate()
, which is also an attribute:
>>> c.conjugate <built-in method conjugate of complex object at 0x7f4422d73050> >>> c.conjugate() (3-4j)
Square bracket notation is used for accessing members of a collection, whether that's by key in the case of a dictionary or other mapping:
>>> d = {'a': 1, 'b': 2} >>> d['a'] 1
... or by index in the case of a sequence like a list or string:
>>> s = ['x', 'y', 'z'] >>> s[2] 'z' >>> t = 'Kapow!' >>> t[3] 'o'
These collections also, separately, have attributes:
>>> d.pop <built-in method pop of dict object at 0x7f44204068c8> >>> s.reverse <built-in method reverse of list object at 0x7f4420454d08> >>> t.lower <built-in method lower of str object at 0x7f4422ce2688>
... and again, in the above cases, these attributes happen to be methods.
While all objects have some attributes, not all objects have members. For example, if we try to use square bracket notation to access a member of our complex number c
:
>>> c[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'complex' object is not subscriptable
... we get an error (which makes sense, since there's no obvious way for a complex number to have members).
It's possible to define how []
and .
access work in a user-defined class, using the special methods __getitem__()
and __getattr__()
respectively. Explaining how to do so is beyond the scope of this question, but you can read more about it in the Python Tutorial.
.
is used for accessing attributes (including methods). []
is used for accessing what are called "items", which typically are the contents of various kinds of container objects.
JavaScript does not distinguish these two things, but Python does. You are correct that []
is used for accessing the data in a list or dict. .
is used, for instance, for accessing methods like list.append
and dict.update
. It is also used for accessing other data on other kinds of objects; for instance, compiled regular expression objects have a pattern
attribute holding the regex pattern (you would access it with rx.pattern
).
In general, the convention is that []
is used for "open-ended" data storage where you don't know ahead of time how much or what sorts of data the object will hold; .
is more commonly used for specific data that the object has "by nature" and which is accessed with a predefined name. For instance, just knowing that something as a list doesn't tell you what's in it (for which you use []
), but it does tell you that you can append to it (and to access the append method you use .
).
The other major difference between Python and JavaScript in this regard is that in Python, the behavior of both .
and []
can be customized by the object. So obj.foo
or obj[foo]
may do something special if obj
is an object that defines its own behavior for them. There are various custom types that make use of this for their own purposes.
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