ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Asterisk(*) of Python
    DynamicPL/Python 2019. 10. 18. 16:15

    1. Overview

    There are 4 cases for using the asterisk in Python.

    • For multiplication and power operations.
    • For repeatedly extending the list-type containers.
    • For using the variadic arguments. (so-called “packing”)
    • For unpacking the containers.

    Let’s look at each case.

    2. Description

    2.1 For multiplication and power operations

    >>> 2 * 3 
    6 
    >>> 2 ** 3 
    8 
    >>> 1.414 * 1.414 
    1.9993959999999997
    >>> 1.414 ** 1.414
    1.6320575353248798

    2.2 For repeatedly extending the list-type containers

    # Initialize the zero-valued list with 100 length
    zeros_list = [0] * 100 
    
    # Declare the zero-valued tuple with 100 length
    zeros_tuple = (0,) * 100  
    
    # Extending the "vector_list" by 3 times
    vector_list = [[1, 2, 3]] 
    for i, vector in enumerate(vector_list * 3):     
        print("{0} scalar product of vector: {1}".format((i + 1), [(i + 1) * e for e in vector]))
    # 1 scalar product of vector: [1, 2, 3]
    # 2 scalar product of vector: [2, 4, 6]
    # 3 scalar product of vector: [3, 6, 9]

    2.3 For using the variadic arguments. (so-called “packing”)

    There are 2 kinds of arguments in Python, one is positional arguments and the other is keyword arguments, the former are specified according to their position and latter are the arguments with a keyword which is the name of the argument.

    2.3.1 Without variadic arguments

    # A function that shows the results of running competitions consisting of 2 to 4 runners.
    def save_ranking(first, second, third=None, fourth=None):
        rank = {}
        rank[1], rank[2] = first, second
        rank[3] = third if third is not None else 'Nobody'
        rank[4] = fourth if fourth is not None else 'Nobody'
        print(rank)    
    
    # Pass the 2 positional arguments
    save_ranking('ming', 'alice')
    # Pass the 2 positional arguments and 1 keyword argument
    save_ranking('alice', 'ming', third='mike')
    # Pass the 2 positional arguments and 2 keyword arguments (But, one of them was passed as like positional argument)
    save_ranking('alice', 'ming', 'mike', fourth='jim')

    The above function has 2 positional arguments: first, second and 2 keyword arguments: third, fourth. For positional arguments, it is not possible to omit it, and you must pass all positional arguments to the correct location for each number of arguments declared. However, for keyword arguments, you can set a default value of it when declaring a function, and if you omit the argument, the corresponding default value is entered as the value of the argument. That is, the keyword arguments can be omitted.

    def save_ranking(first, second=None, third, fourth=None):
        ...

    2.3.2 When using only positional arguments

    def save_ranking(*args):
        print(args) 
    save_ranking('ming', 'alice', 'tom', 'wilson', 'roy')
    # ('ming', 'alice', 'tom', 'wilson', 'roy')

    2.3.3 When use only keyword arguments

    def save_ranking(**kwargs):
        print(kwargs)
    save_ranking(first='ming', second='alice', fourth='wilson', third='tom', fifth='roy')
    # {'first': 'ming', 'second': 'alice', 'fourth': 'wilson', 'third': 'tom', 'fifth': 'roy'}
    

    2.3.4 When using both positional arguments and keyword arguments

    def save_ranking(*args, **kwargs):
        print(args)     
        print(kwargs)
    save_ranking('ming', 'alice', 'tom', fourth='wilson', fifth='roy')
    # ('ming', 'alice', 'tom')
    # {'fourth': 'wilson', 'fifth': 'roy'}

    2.3.5 Exception case

    The keyword arguments can not be declared before positional arguments, so the following code should raise exceptions:

    def save_ranking(**kwargs, *args):
        ...

    2.4 For unpacking the containers

    The * can also be used for unpacking the containers. Its principles are similar to “For using the variadic arguments” in above. The easiest example is that we have data in the form of a list, tuple or dictionary, and a function takes variable arguments:

    from functools import reduce
    
    primes = [2, 3, 5, 7, 11, 13]
    
    def product(*numbers):
        p = reduce(lambda x, y: x * y, numbers)
        return p 
    
    product(*primes)
    # 30030
    
    product(primes)
    # [2, 3, 5, 7, 11, 13]

    Because the product() take the variable arguments, we need to unpack our list data and pass it to that function. In this case, if we pass the primes as *primes, every element of the primes list will be unpacked, then stored in list called numbers. If pass that lists primes to the function without unpacking, the numbers will have only one prime list not all elements of primes.

    3. References

    https://medium.com/understand-the-python/understanding-the-asterisk-of-python-8b9daaa4a558

    https://en.wikipedia.org/wiki/Variadic_function#targetText=In%20mathematics%20and%20in%20computer,neologism%2C%20dating%20back%20to%201936.

    댓글

Designed by Tistory.