Hacker News new | ask | show | jobs
by youngerdryas 4874 days ago
Neat little story, despite the grammar and capitalization. Is it common to use _ as an index variable?

Edit: for _ in range(4):

6 comments

Not sure how common that is, but I've seen it used before where the index variable itself is not referenced inside the body of the statement.
Common in Lua, Ruby, Python. In fact, ruby gives _ a minor amount of special meaning to make it more convenient as a throw-away variable, e.g. it can be specified multiple times in an argument list without an error and generates no warning if left unused.
I've seen it before, but it's a little jarring. Not sure what's wrong with just using i.
It says explicitly that you don't care about that value. If you used i, for example, you wouldn't know whether the loop depended on the iteration number.
Yeah, I get it. And that's a useful thing to do, I guess. It just seems a little... unpythonic.
To avoid unused variable warnings.
It's better to use two underscores __ to represent throwaway variables, because _ has a meaning in Python: it returns the last output.
True, but only in the REPL.

For example try to run the following script (not from the REPL):

  _ = 12
  print _
  42 * 42
  print _
Most of the code is a little verbose for Python. For example make() function could simply be:

    return [random.randint(1,10000) for x in range(4)]
Also remember that a little kitten dies every time you write a for loop as follows:

    for index in range(len(some_list)):
I'm a python noob. Why does a kitten die? You're creating a new list of the same size of the source list (once) and iterating over it. How can you achieve the same w/out creating a new list?
Python god takes the kitten as a sacrifice for the unnecessary list of indexes you created :).

range(len(some_list)) is a convoluted way iterating over the elements of a list. What you are doing is creating a new list with elements [0,... lengh-1] and iterating over the elements of this list, only to immediately throw them away after using them as array index to grab the item you really want from the original list.

Instead you can just directly iterate over your original list: "for item in some_list". If you really need to know the index value, you can use enumerate: "for index, item in enumerate(some_list)"

One nice thing is that the "for x in y" lets you iterate over things (iterables) that you may be generating on the fly (e.g., all prime numbers smaller than N).

_ is a typical name to use when the language requires a variable name that the program doesn't otherwise need. In this case, the program just needs to run some code four times, and doesn't care about the index. The language doesn't have a plain "run this code X times" construct, but it does have a "iterate over this list" construct, so the code iterates over the list [0, 1, 2, 3] and puts the current element into a dummy variable since it's not being used.