This is intended behavior because i.pop()
is an expression that is evaluated before c.get(...)
is. Imagine what would happen if that weren't the case. You might have something like this:
def myfunction(number):
print("Starting work")
# Do long, complicated setup
# Do long, complicated thing with number
myfunction(int('kkk'))
When would you have int('kkk')
to be evaluated? Would it be as soon as myfunction()
uses it (after the parameters)? It would then finally have the ValueError after the long, complicated setup. If you were to say x = int('kkk')
, when would you expect the ValueError? The right side is evaluated first, and the ValueError occurs immediately. x
does not get defined.
There are a couple possible workarounds:
c.get(0) or i.pop()
That will probably work in most cases, but won't work if c.get(0)
might return a Falsey value that is not None
. A safer way is a little longer:
try:
result = c[0]
except IndexError:
result = i.pop()
Of course, we like EAFP (Easier to Ask Forgiveness than Permission), but you could ask permission:
c[0] if 0 in c else i.pop()
(Credits to @soon)