0

Today I randomly realized you can add an index after print() in python, which behaves pretty much as if it was applied to a list passed as a parameter to print.

>>> sublists = [[['a'],['b'],['c']],[['d'],['e'],['f']],[['g'],['h'],['i']]]
>>> print(sublists[1][1])
['e']
>>> print(sublists[1])[1]
['e']
>>> print(sublists)[1][1]
['e']

>>> string = 'abcdefgh'
>>> print(string)[3:6]
def

I couldn't find any documentation explaining this behavior nor examples of what is it good for. What's going on, here?

  • `print(...)[3:6]` will **not work** unless you replaced the built-in `print()` implementation: `TypeError: 'NoneType' object is not subscriptable`. – Martijn Pieters Apr 27 '17 at 12:02
  • Only if you replaced the built-in `print()` function with one that returns something other than `None` would your output look like that. You can use `[...]` subscription syntax after *any* expression that produces a sequence however, including function calls. – Martijn Pieters Apr 27 '17 at 12:04
  • Martijn: in Python2 `print` is a statement, so it works.. – Eugene Yarmash Apr 27 '17 at 12:06
  • Ah, it dawns on me that you are probably using **Python 2** here, where `print` is a *statement*, not a function. You are printing the result of `(string)[3:6]` here. You'd get the same result with `print string[3:6]`, the parentheses only serve to group the `string` expression (and to make you get away with not using a space between `print` and the expression). – Martijn Pieters Apr 27 '17 at 12:06
  • 1
    @eugeney: yup, already got there, at which point the question is also moot; `print` is not a function unless you use `from __future__ import print_function` in that case, and all the OP is doing is adding otherwise redundant `(...)` parentheses. – Martijn Pieters Apr 27 '17 at 12:07
  • I found a suitable duplicate that explains what the parentheses do in this case. – Martijn Pieters Apr 27 '17 at 12:09
  • Okay, that indeed does explain it! – Milan Troller Apr 27 '17 at 12:10

0 Answers0