Tip 10 Mark Dummy Variables

Pythonic Programming — by Dmitry Zinoviev (18 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Let input() Speak for Itself | TOC | Distinguish Parameters and Arguments 👉

★2.7, 3.4+ Some looping statements in Python (for example, for and list/dictionary/set comprehension) require that you declare a temporary, dummy variable — a loop variable. The loop variable is created and updated automatically. It is meant to be used in the body of the loop, but it is wasted in some situations. This loop prints the same message “Hello world!” four times (there are better ways to do this, see Tip 63, Build, Then Print). The content of the message does not depend on the iteration number:

​ ​for​ i ​in​ range(4):
​ ​print​(​'Hello world!'​)
​=> ​Hello world!​
​=> ​Hello world!​
​=> ​Hello world!​
​=> ​Hello world!​

There may be other situations where you do not plan to use a variable but have to define it anyway. In either case, you would like to inform the code reader that the variable should be ignored. Python has a memorable name reserved for such variables: a single underscore _.

​ ​for​ _ ​in​ range(4):
​ ​print​(​'Hello world!'​)
​=> ​Hello world!​
​=> ​Hello world!​
​=> ​Hello world!​
​=> ​Hello world!​

Yes, it is a legal identifier (see Tip 5, Keep Letter Case Consistent for details).

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.