Federico Ponzi
Federico Ponzi

Reputation: 2785

Two square brackets side by side: strange effect

I was on a competitive programming site, and found a guy who wrote this strange (to me) Python 3 code:

[r,"Nothing"][r==""]

It outputs 'Nothing', if r is the empty string.

How is this called and what does it mean? It looks like a ternary operator.

Upvotes: 3

Views: 370

Answers (2)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160657

How is this called and what does it mean? It looks like a ternary operator.

There's no official name for it in Python AFAIK; it's just a sneaky, convoluted way of indexing a list, really.

You'll select "Nothing" if r=="" is True and r if r == '' is False; as an example:

>>> [0, 1][True]
1
>>> [0, 1][False]
0

since True and False are interpreted as 1 and 0 respectively, when you index the list.

The snippet provided just defines a temporary list with the two elements [r, "Nothing"] and then indexes it using the True/False result of the comparison of r with the empty string [r==''].

Not the most readable code and probably not the best idea to create a list which you don't plan on using; it can be easily substituted by the conditional expression:

"Nothing" if r == "" else r

more readable and a lot more efficient:

%timeit True if False else False
10000000 loops, best of 3: 32.9 ns per loop

%timeit [False, True][False]
10000000 loops, best of 3: 176 ns per loop

no need to create a list and no need to subscript it; just a conditional and some loading.

Upvotes: 5

fredtantini
fredtantini

Reputation: 16586

It translates to:

if (r==""):
  'Nothing'
else:
  r

False in this context is used as 0, and True as 1:

>>> [r,'Nothing'][False]
'foo'
>>> [r,'Nothing'][True]
'Nothing'

It's a one-liner similar to 'condition'?'if true':'if false' in other languages. It's usually used in code golf where you have to produce the shortest code possible.

Upvotes: 1

Related Questions