Jul 31, 2024
_): Used as a placeholder for variables whose values are not needed.for _ in range(10):
print("Do this")
x, _ = coordinate
x, _, z = larger_coordinate
second_elements = [b for _, b in list_of_pairs]
else block executes only if the loop is not terminated by a break statement.for item in items:
if item == 'B':
break
else:
print("Do something here")
else block runs if 'B' is not found and loop completes.:= (introduced in Python 3.8).while (data := next(generator)) != -1:
process(data)
results = [result for x in range(10) if (result := f(x)) > 3]
*): Unpacks iterable objects (e.g., lists, tuples).
def func(a, b, c, d):
pass
values = [1, 2, 3, 4]
func(*values)
**): Unpacks dictionaries for keyword arguments.
def func(key, target):
pass
kwargs = {'key': 5, 'target': 10}
func(**kwargs)
collections module.defaultdictfrom collections import defaultdict
def default():
return 0
char_count = defaultdict(default)
for char in string:
char_count[char] += 1