Search code examples
pythonpython-3.xfunctionconditional-operator

"return" with Ternary and warlus operators


Why when I try to return value with warlus and ternary operators := like this:

def get_index(elements: List[int], i: int, boundary: int) -> tp.Optional[int]:
    return x := elements[i] if elements[i] > boundary else None

I get an error.


Solution

  • The comments suggest that you can't use the walrus operator in a return statement, that's incorrect - you just have a syntax error.

    This works, but is pointless, as also pointed out in the comments:

    from typing import List, Optional
    
    
    def get_index(elements: List[int], i: int, boundary: int) -> Optional[int]:
        return (x := elements[i] if elements[i] > boundary else None)
    
    
    print(get_index([1, 2, 3], 2, 1))
    

    All you need is parentheses around the walrus assignment and the value of the expression will be the assigned value.

    But why assign to x if all you do is return that value. Instead:

    from typing import List, Optional
    
    
    def get_index(elements: List[int], i: int, boundary: int) -> Optional[int]:
        return elements[i] if elements[i] > boundary else None
    
    
    print(get_index([1, 2, 3], 2, 1))