Python Anonymous Variable

Anonymous Variables are one of the features of Python that is rarely used by the developers/coders.

Anonymous Variables are declared using "_" and used when values don't matter in the further process. eg

_ = 20        

Now let's see some examples where this can be useful

def get_info(a->List):
    return a[0], a[1]

first_elem, _ = get_info([1,2])
           

In the above example, get_info function takes List as input and returns the first two elements.

Now if you only need 1st element of the list and not 2nd. In this case, you can use an anonymous variable ("_") and ignore the 2nd element.

Saurabh Agrawal

Technical Lead | Ex- Playo | Ex- StepSetgo

1 年

This is also used in golang, the compiler throws an error in case of an unused variable, but ignores _ vars.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了