Skip to main content

One-Liners

1) Multiple Variable Assignment
# Traditional way
a = 1
b = "ok"
c = False
 
# Pythonic way
a, b, c = 1, "ok", False
 
# Result
print(a, b, c)
# Show: 1 ok False
2) Variable Swap
# Traditional way
a = 1
b = "ok"
 
c = a
a = b
b = c
 
# Pythonic way
a, b = 1, "ok"
a, b = b, a
 
# Result
print(a, b)
# Shows: ok 1
# Pythonic way
a, b, c, d = 1, "ok", True, ["i", "j"]
a, b, c, d = c, a, d, b
 
# Result
print(a, b, c, d)
# Shows: True 1 ["i", "j"] ok
3) Variable Conditional Assignment
x = 3
 
# Traditional way
if x % 2 == 1:
result = f"{x} is odd"
else:
    result = f"{x} is even"
 
# Pythonic way
result = f"{x} " + ("is odd" if x % 2 == 1 else "is even")
 
# Result
print(result)
# Shows: 3 is odd
4) Presence of a Value in a List
pet_list = ["cat", "dog", "parrot"]
 
# Traditional way
found = False
for item in my_list:
    if item == "cat":
        found = True
        break
 
# Pythonic way
found = "cat" in pet_list
 
# Result
print(found)
# Shows: True
pet_dict = {"cat": "Mitchi", "dog": "Max", "parrot": "Pepe"}
found = "cat" in pet_dict
print(found)
# Shows: True