:=
)The Walrus operator (:=
) allows you to assign a value to a variable as part of an expression — combining assignment and condition check in one line.
if (n := len(my_list)) > 3:
print(f"List is too long ({n} elements)")
# Old Way
n = len(my_list)
if n > 3:
...
# With Walrus
if (n := len(my_list)) > 3:
...
# walrus.py
if(n := len([1,2,3,4,5])) > 3:
print(f"List is too long({n} elements, expected < 3)")
else:
print("List is shorter than 3 elements")
Type Hints provide information to the reader and IDEs about what type a variable/function expects. It doesn't enforce anything but makes the code easier to understand and maintain.
def func(a: int, b: int) -> int:
return a + b
# typehints.py
from typing import Tuple
n: int = 5
name: str = "Prathamesh"
def sum(a: int, b: int) -> int:
return a + b
person: tuple[int, str] = ("Prathamesh", 100)
print(sum(5, 5))
print(person, type(person))