Is there a more elegant way to spell this?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jan 28 01:55:58 CET 2015


Neal Becker wrote:

> Is there a more elegant way to spell this?
> 
> for x in [_ for _ in seq if some_predicate]:

Don't use _ as the loop variable here.

There are three common conventions for _ and this is none of them:


(1) n the interactive interpreter _ is used for the result of the last
expression:

py> 1+2
3
py> _ * 2
6

(2) In locale-aware applications, _ is apparently used as a function for
localising text into the user's native language.

(3) _ is also commonly used as a "don't care" variable name:

a, _, b, _ = get_four_items()  # but I only care about two of them


So in a loop, you would only use _ as the loop variable when you don't use
the loop variable, e.g.:

[random.random() for _ in range(10)]


Of course, a convention is just a convention, not a law, you can ignore such
conventions if you insist. But conventions make it easier and quicker to
understand code, not just for others, but for yourself as well.


-- 
Steven




More information about the Python-list mailing list