-4

What does the following line of code mean in Python?

id = result and result[1] or False

Note: This question combines both operators "and" and "or". However, other questions asked in "Stackoverflow" take into account having only one of those operators in the statement.

Ababneh A
  • 1,104
  • 4
  • 15
  • 32

3 Answers3

1

It appears that this is to avoid IndexError being raised if the sequence result (e.g. list, tuple) contains fewer than 1 item. But, if this is the intention, it is flawed because Python sequences are 0-based and result[1] accesses the second item in the sequence. Checking that the list is not empty does not guarantee that a second item exists. Probably the intention is to check that there is at least one item in the sequence and to get the first item in the sequence, not the second.

And, due to short-circuiting, the or False is actually superfluous anyway.

It is a shorthand way of doing this if statement:

if result:
    id = result[1]
else:
    id = False

but as I said it seems flawed. This would be better:

try:
    id = result[1]
except IndexError:
    id = False

or perform a length check:

if len(result) > 1:
    id = result[1]
else:
    id = False

or:

id = result[1] if len(result) > 1 else False

or to continue the horrible inline method in the question:

id = (len(result) > 1) and result[1]

Which just highlights that code should not be written in the manner shown the question: it is not immediately clear what the intention and outcome of the code is, and some thought is required to understand it. An if statement is much more readable so it should be used.

mhawke
  • 84,695
  • 9
  • 117
  • 138
  • Also worth noting perhaps that it's not **exactly** the same as your `if` statements if `result[1] = 0` for example. – donkopotamus Dec 14 '15 at 08:41
0

Here's an equivalent Python code for that line:

if result:
    id = result[1]
else:
    id = False

It basically means:

If result evaluates to True, assign id the second element of result list, else assign id the boolean value False

Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84
0

That code assign result[1] item (second item of list or second letter rom string) to id variable if it exists otherwise False would be assigned to id.

Note In case if result list containing only 1 item that code would fail with IndexError.

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82