Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 284
Federico Ponzi Avatar asked May 04 '26 16:05

Federico Ponzi


1 Answers

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.

like image 54
Dimitris Fasarakis Hilliard Avatar answered May 07 '26 04:05

Dimitris Fasarakis Hilliard