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
5) Operations on Lists
my_list = [1, 2, 3, 4, 5]
# Traditional way
max_value = 0
for value in my_list:
if value > max_value:
max_value = value
# Pythonic way
max_value = max(my_list)
# Result
print(max_value)
# Shows: 5
6) List Creation with Duplicate Values
size = 10
# Traditional way
my_list = []
for i in range(size):
my_list.append(0)
# Pythonic way
my_list = [0] * size
# Result
print(my_list)
# Shows: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
my_list = [1, 2] * 5
# Result: [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
my_tuple = (1, 2) * 5
print(my_tuple)
# Shows: (1, 2, 1, 2, 1, 2, 1, 2, 1, 2)