Post

Python Tips

Python Tips

** Special Usages

1. Unpacking a dictionary into keyword arguments in a function call

1
2
3
4
5
def greet(name, age):
    print(f"Hello, {name}, You are {age} years old.")

person = {"name": "Alice", "age": 30}
greet(**person)

Output:

1
Hello, Alice. You are 30 years old.

2. Merging two dictionaries

1
2
3
4
5
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

merged_dict = {**dict1, **dict2}
print(merged_dict)

Output:

1
{'a': 1, 'b': 3, 'c': 4}

Notice that the overlapping key ‘b’, its value is overwritten by dict2.

* Special Usages

1. Unpacking Iterables

1
2
3
4
5
6
def add(a, b, c):
    return a + b + c

nums = [1, 2, 3]
result = add(*nums)
print(result)

Output:

1
6

2. Variable-Length Function Arguments

1
2
3
4
5
def print_all(*args):
    for arg in args:
        print(arg)

print_all(1, 2, 3, 4)

Output:

1
2
3
4
1
2
3
4

3. Unpacking in Iterables

1
2
3
a = [1, 2, 3]
b = [*a, 4, 5]
print(b)

Output:

1
[1, 2, 3, 4, 5]

4. Keyword-Only Arguments

1
2
3
4
5
def func(a, *, b):
    return a + b

# func(1, 2) -> Error, func() takes 1 positional argument but 2 were given
func(1, b=2) # works

5. List/Iterable Multiplication

1
repeated = [1, 2, 3] * 3

BTW, be careful when using this syntactic sugar because it may create references to the same object.

1
2
3
4
repeated = [[1, 2, 3]] * 3
print(repeated)
repeated[0][0] = 6
print(repeated)

References

This post is licensed under CC BY 4.0 by the author.