Skip to main content

Role of Underscore(_) in Python Tutorial

In this tutorial, you're going to learn about the uses of underscore(_) in python.
· 8 min read

Explore with AI

Run and edit the code from this tutorial online

Run code

Many of the Python Developers don't know about the functionalities of underscore(_) in Python. It helps users to write Python code productively.

Underscore(_) is a unique character in Python.

If you're a Python programmer, you probably familiar with the following syntax:

  • for _ in range(100)

  • __init__(self)

  • _ = 2

It has some special meaning in different conditions. Let's see all of those.

You will find max six different uses of underscore(_). If you want you can use it for different purposes after you have an idea about underscore(_).

1. Use in Interpreter

Python automatically stores the value of the last expression in the interpreter to a particular variable called "_." You can also assign these value to another variable if you want.

You can use it as a normal variable. See the example

>>> 5 + 4
9
>>> _     # stores the result of the above expression
9
>>> _ + 6
15
>>> _
15
>>> a = _  # assigning the value of _ to another variable
>>> a
15

2. Ignoring Values

Underscore(_) is also used to ignore the values. If you don't want to use specific values while unpacking, just assign that value to underscore(_).

Ignoring means assigning the values to special variable underscore(_). We're assigning the values to underscore(_) given not using that in future code.

See the example

## ignoring a value
a, _, b = (1,