Four Usage Scenarios of Underscores in Python

Yang Zhou
Yang Zhou
Jun 6, 2020 · 4 min read
Four Usage Scenarios of Underscores in Python
Four Usage Scenarios of Underscores in Python
Photo by Dan Meyers on Unsplash

Introduction

Separate Digits of Numbers

>>> a = 1_000_000_000_000
>>> a
1000000000000

Use to Ignore Some Variable

>>> L = [1,3,5,7]
>>> a, _, b, _ = L
>>> print(a, b)
1 5

Store the Last Expression’s Value in Interpreter

>>> 5+6
11
>>> _
11

Naming Conventions

first_name = 'Yang'

Single/Double Leading Underscore

class Student:
def __init__(self, name, age, grade):
self.name = name # public member
self._age = age # protected member
self.__grade = grade # private member

Single Trailing Underscore

>>> list_ = [1,2,3] # good naming style
>>> list = [2,3,4] # bad name; has ambiguity with Python keyword

Double Leading and Trailing Underscore

Conclusion

TechToFreedom

Dive into technology, investment and entrepreneurship.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store