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
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
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
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.
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.