Using the * and ** unpacking operators in Python
In Python, the * and ** operators can be used to unpack elements of an iterable or dictionary, respectively.
The * operator is used to unpack iterables such as lists, tuples, and strings. It can be used in a function call to pass elements of a list or tuple as separate arguments. For example, consider the following code:
def myfunc(a, b, c):
print(a, b, c)
mylist = [1, 2, 3]
myfunc(*mylist)
In this code, the list mylist
is unpacked using the * operator and passed as separate arguments to the function myfunc
. The output of this code would be:
1 2 3
The ** operator is used to unpack dictionaries. It can be used to pass the key-value pairs of a dictionary as keyword arguments to a function. For example, consider the following code:
def myfunc(a, b, c):
print(a, b, c)
mydict = {'a': 1, 'b': 2, 'c': 3}
myfunc(**mydict)
In this code, the dictionary mydict
is unpacked using the ** operator and passed as keyword arguments to the function myfunc
. The output of this code would be:
1 2 3
Another example of using * operator can be in a list, for example:
my_list = [1, 2, 3, 4, 5]
head, *tail = my_list
print(head) # Output: 1
print(tail) # Output: [2, 3, 4, 5]
In this code, the * operator is used to unpack the remaining elements of the list into tail
after the first element has been assigned to head
. The output of this code would be:
1
[2, 3, 4, 5]
Overall, unpacking operators are very useful in Python for working with iterables and dictionaries in a more flexible and concise manner.