Search
  • Team FastApp

Python3.8 - The Walrus Operator

In Python 3.8, we will be able to use assignment as a part of the large expressions. It has a new syntax :=

Examples:

1. if-else block


Python3.8

my_string = "second"
if (my_var := len(my_string)) > 5:     
    print(f"Error!! String is too long, ({my_var} elements, expected <= 5)")

< Python3.8

if len(my_string) > 5: 
    print(f"Error!! List is too long ({len(my_string)} elements, expected <= 5)")

Thus need to call len() twice here. After Walrus operator's introduction this can be

one call to len() only. Thus this reduces the line count of code by 1.



2. In while-loop:

Python3.8

while (password := input("Enter the password: ")) != "my password":
    continue

< Python3.8

while True:
    password = input("Enter the password: ")   # extra line 
    if (password != "my password"):
        continue

here we save one line by using the Walrus Operator.



3. In for-loops:


Python 3.8

numbers = [11, 22, 33, 44]
accepted_numbers = [
    result 
    for number in numbers 
    if (result := call_some_function(number)) > 0
]

< Python 3.8

numbers = [11, 22, 33, 44] 
accepted_numbers = [
    call_some_function(number) 
    for number in numbers      
    if (result := call_some_function(number)) > 0 
]

Notice that this is not a good practise as we need to call call_some_function(number) twice

in the comprehension.




31 views1 comment

Recent Posts

See All

Python3.6 - What the f-string !

In Python 3.6, there is a new way to format the strings, which helps the user in faster coding, less googling, and better readable code. Which was previously a little tedious by using %-format or even

 

©2020 by FastApp. Created with <3