MrD
MrD

Reputation: 5084

Python printing list element

I noticed that in the following snippet both approaches give the same result:

>>> a = [1,2,3]
>>> print(a[0])
1
>>> print(a)[0]
1
>>> 

I was a bit surprised, as I would have expected print(a) to return a string, so then subscript 0 to just return the first character (Ie: [). However, it seems Python interprets it as a list?

Anybody able to clarify please?

Upvotes: 2

Views: 68

Answers (2)

Slam
Slam

Reputation: 8582

As mentioned, you're using python 2.x, where print is a statement, not a function — so print(a)[0] being parsed as print a[0] — treating braces as parsing priority modifier.

Important thing — print does not return what you're printing. It sends data to stream (stdout by default). If you're using python 3.x (where print is a function) or use from __future__ import print_function — functions will send data to stream and return None as result. So print(a)[0] will resolve to "send content of a to stdout and return None[0]", later will raise IndexError

Upvotes: 4

user10640506
user10640506

Reputation:

As @jonrsharpe mentioned in the comment block, you're probably running python 2.x.

print statement was replaced in python 3.x with print() function

>>> print(a)[0]
[1, 2, 3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not subscriptable


Upvotes: 1

Related Questions