2

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?

2
  • 2
    In Python3, I see print(a)[0] giving TypeError: NoneType is not subscriptable. Commented Feb 5, 2019 at 11:23
  • 9
    You're using Python 2.x, so the parentheses are redundant in both cases (print is a statement, not a function) - it's always print a[0]. (a[0]) is (a)[0] is a[0]. Commented Feb 5, 2019 at 11:23

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

s/probably/definitely/ - as @jpp pointed out, the second snippet would be a TypeError (not an IndexError as you state) in Python 3.
Edited. Normally, I don't write about my assumptions as if it reality — maybe that's some exotic version of python built from scratch ;)
1

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


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.