1. Unpacking iterables into a list/tuple
In addition to serving as the symbol for multiplication, the star operator (*) in Python has several other applications. The first application is unpacking iterables into a list/tuple
Example: Adding (appending) elements to an array
>>> n = [2, ,3, 4, 5, 6, 1] >>> n [2, 3, 4, 5, 6, 1] >>> m = [n, 2] >>> m [[2, 3, 4, 5, 6, 1], 2]
instead,
>>> n = [2,3,4,5,6,1] >>> n [2, 3, 4, 5, 6, 1] >>> m = [*n, 2] >>> m [2, 3, 4, 5, 6, 1, 2]
Another example:
>>> chars = ['a', 'b', 'c', 'd'] >>> print(chars) ['a', 'b', 'c', 'd'] >>> print(chars[0], chars[1], chars[2], chars[3]) a b c d >>>print(*chars) a b c d
2. Packing function arguments
The star operator can be used for packing arguments sent to a function. In other words, we can develop functions that can accept any number of arguments. For instance,
>>> def collect_all(*n): return sum(n) >>> collect_all(1) 1 >>> collect_all(1,2,3) 6 >>>
The star or asterisk operator has other applications that we will discuss in another post.