Eamonn
Eamonn

Reputation: 710

Make an "actual" for loop in Python?

As you should know, in Python, the following is a valid for loop in Python:

animals = [ 'dog', 'cat', 'horse' ] # Could also be a dictionary, tuple, etc

for animal in animals:
    print animal + " is an animal!"

And this is usually fine. But in my case, I want to make a for loop like the way you would in C/C++/Java etc. The for loop that looks like this:

for (int x = 0; x <= 10; x++) {
    print x
}

How could I do something like this in Python? Would I have to set up something like this, or is there an actual way to do this that I'm missing (I've googled for a good few weeks):

i = 0

while i is not 10:
    print i

Or is there a standard of how to do this? I find the above does not always work. Yes, for the case of the above I could do:

for i in range(10):
    print i

But in my case I can't do this.

Upvotes: 1

Views: 410

Answers (2)

9000
9000

Reputation: 40894

Why would you need a C-style index-tracking loop? I can imagine a few cases.

# Printing an index
for index, name in enumerate(['cat', 'dog', 'horse']):
  print "Animal #%d is %s" % (index, name)

# Accessing things by index for some reason
animals = ['cat', 'dog', 'horse']
for index in range(len(animals)):
  previous = "Nothing" if index == 0 else animals[index - 1]
  print "%s goes before %s" % (previous, animals[index])

# Filtering by index for some contrived reason
for index, name in enumerate(['cat', 'dog', 'horse']):
  if index == 13:
    print "I am not telling you about the unlucky animal"
    continue  # see, just like C
  print "Animal #%d is %s" % (index, name)

If you're hell-bent on emulating a counter-tracking loop, you've got a Turing-complete language, and this can be done:

# ...but why?
counter = 0
while counter < upper_bound:
  # do stuff
  counter += 1

If you feel compelled to reassign the loop counter variable mid-loop, chances are high that you're doing it wrong, be it a C loop or a Python loop.

Upvotes: 9

shash
shash

Reputation: 965

I guess from your comment that you're trying to loop over grid indices. Here are some ways:

Plain simple double for loops:

for i in xrange(width):
    for j in xrange(height):
         blah

Using itertools.product

for i, j in itertools.product(xrange(width), xrange(height)):
     blah

Using numpy if you can

x, y = numpy.meshgrid(width, height)
for i, j in itertools.izip(x.reshape(width * height), y.reshape(width * height):
    blah

Upvotes: 9

Related Questions