4 ms·
Python noob here. What does the _ mean in "...for _ in range(100))"?
by frindo 12y ago
Python noob here. What does the _ mean in "...for _ in range(100))"?
- icebraining 12y agoIt's just a name of a variable. There's nothing special about it (in this context), but it's conventionally used when you don't care about the value assigned to it.
- ixwt 12y agoNormally you would place a variable there, such as x or y. But in this case, the variable doesn't matter. You aren't using it in the function call. You're telling the programming the variable for the for loop that it doesn't matter.
- danudey 12y agoTo add to specifics: _ in python is commonly used as a variable name for values you want to throw away. For example, let's say you have a log file split on newlines, with records like this: logline = "127.0.0.1 localhost.example.com GET /some/url 404 12413" You want to get all the URLs that are 404s, but you don't care about who requested them, etc. You could do this: _, _, _, url, returncode, _ = logline.split(' ') There's no special behaviour for _ in this case; in fact, normally in the interactive interpreter it's used to store the result of the last evaluated line, like so: >>> SomeModel.objects.all() [SomeModel(…), SomeModel(…), SomeModel(…), …] >>> d = _ >>> print d [SomeModel(…), SomeModel(…), SomeModel(…), …] Which I think is basically the same behaviour; you run some code, you don't assign it, so the interpreter dumps it into _ and goes on about its day.