Search code examples
pythonreturnconditional-statements

one line return condition


that's my code:

d = {'key1':1,'key2':5}

def pop1(d):
    return d.pop('key2') if len(d) > 1 else d

def pop2(d):
    if len(d) > 1: d.pop('key2')
    return d

def test(a):
    return a, len(a)

pop2 works fine:

print test(pop2(d))

({'key1': 1}, 1)

pop1 doesn't:

print test(pop1(d))

TypeError: object of type 'int' has no len()

What am I missing? Is it about the pop() function or the one-line condition?


Solution

  • If we analyse the following return statement:

    d.pop('key2') if len(d) > 1 else d
    

    we see that when the length of the dictionary is less than 1, the dictionary is just returned. This is not the case here, so we are interested when len(d) is > 1.

    In this case, d.pop('key2') is returned. From the documentation, we see that the .pop method will:

    If key is in the dictionary, remove it and return its value

    ...so pop1 will return the value of 'key2' which is 5.

    This leads to an error when you call len() on it since 5 is an integer.

    This is made clear by the error:

    TypeError: object of type 'int' has no len()


    Why does pop2() work?

    Well this function does not use a ternary which decides whether the value or the whole dictionary is returned, instead we always return d - the dictionary.

    This means that len() can always be called and it works as expected.