4

I am wondering if Python has the concept of storing data in the default variable in for loop.

For example, in perl, the equivalent is as follow

foreach (@some_array) {
    print $_
}

Thanks, Derek

defoo
  • 5,159
  • 11
  • 34
  • 39
  • 2
    There is not, and there should not be. "Explicit is better than implicit". For other pratices, stick with other languages. This is one of the worst part of Perl. – jsbueno Nov 22 '10 at 17:17

4 Answers4

15

No. You should just use

for each in some_array:
    print each
dave
  • 12,406
  • 10
  • 42
  • 59
2

Just for fun, here's something that does just about what you desire. By default it binds the loop variable to the name "_each", but you can override this with one of your own choosing by supplying a var keyword argument to it.

import inspect

class foreach(object):
    __OBJ_NAME = '_foreach'
    __DEF_VAR = '_each'

    def __init__(self, iterable, var=__DEF_VAR):
        self.var = var
        f_locals = inspect.currentframe().f_back.f_locals
        if self.var not in f_locals:  # inital call
            self.iterable = iter(iterable)
            f_locals[self.__OBJ_NAME] = self
            f_locals[self.var] = self.iterable
        else:
            obj = f_locals[self.__OBJ_NAME]
            self.iterable = obj.each = obj.iterable

    def __nonzero__(self):
        f_locals = inspect.currentframe().f_back.f_locals
        try:
            f_locals[self.var] = self.iterable.next()
            return True
        except StopIteration:
            # finished - clean up
            del f_locals[self.var]
            del f_locals[self.__OBJ_NAME]
            return False

some_array = [10,2,4]
while foreach(some_array):
    print _each

print
while foreach("You can do (almost) anything in Python".split(), var='word'):
    print word
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Unfortunately, like all of these hacks using `f_locals`, it only works in the global scope. If you want to use it deeper in a function, you have to use one more `f_back` for each additional level. Eventually you figure out that you're actually just using `globals()`. +1 though. Good trick. – aaronasterling Nov 22 '10 at 21:16
  • @aaronasterling: I know, since I more-or-less got the idea from your answer to [switch case in python doesn't work; need another pattern](http://stackoverflow.com/questions/3886641/switch-case-in-python-doesnt-work-need-another-pattern) -- and our prolonged discussion of it. ;-) Those facts are also why I began my answer here with "Just for fun". – martineau Nov 22 '10 at 22:34
1

Python allows the use of the '_' variable (quotes mine). Using it in a program seems to be the Pythonic way to have a loop control variable that is ignored in the loop (see other questions, e.g. Is it possible to implement a Python for range loop without an iterator variable? or my Pythonic way to ignore for loop control variable). As a comment pointed out, this isn't the same as Perl's default variable, but it allows you to do something like:

some_list = [1, 2, 3]
for _ in some_list:
    print _

A guru may correct me, but I think this is about as close as you'll get to what you're looking for.

Community
  • 1
  • 1
GreenMatt
  • 18,244
  • 7
  • 53
  • 79
  • 6
    No, there is no such default variable. `_` is just another valid name. – Ignacio Vazquez-Abrams Nov 22 '10 at 16:29
  • @Ignacio Vazquez-Abrams: Yeah, you're right, but to me it seems analogous. Answer edited. – GreenMatt Nov 22 '10 at 16:33
  • 2
    `_` only exists in the python shell. http://bytes.com/topic/python/answers/547490-default-variable-python-_#post2136729 The example you give is no different than using a normal variable name. – unholysampler Nov 22 '10 at 16:33
  • @unholysampler: I don't recall using _ in the Python shell before, thanks for pointing that out. FWIW, _ does allow you to avoid pylint warnings about variable names being too short or not used (see the link in my answer to my earlier question). – GreenMatt Nov 22 '10 at 16:50
  • And that's because `_` is the idiomatic name for something you throw away/don't use (e.g. `for _ in range(n): # repeat it n time, don't use the current iteration no.`). So it's inappropriate in your example. –  Nov 22 '10 at 17:11
0

Whatever is used in the for loop syntax becomes the variable that that item in the iteration is stored against for the remainder of the loop.

for item in things:
    print item

or

for googleplexme in items:
    print googleplexme

The syntax looks like this

for <given variable> in <iterable>:

meaning that where given variable can be anything you like in your naming space and iterable can be an iterable source.

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91