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

1
  • 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. Commented Nov 22, 2010 at 17:17

4 Answers 4

15

No. You should just use

for each in some_array:
    print each
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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: I know, since I more-or-less got the idea from your answer to switch case in python doesn't work; need another pattern -- and our prolonged discussion of it. ;-) Those facts are also why I began my answer here with "Just for fun".
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.

5 Comments

No, there is no such default variable. _ is just another valid name.
@Ignacio Vazquez-Abrams: Yeah, you're right, but to me it seems analogous. Answer edited.
_ only exists in the python shell. bytes.com/topic/python/answers/… The example you give is no different than using a normal variable name.
@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).
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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.