1

I found that python doesn't have C style for loop:

  for (var;condition:increment)

For a simple for loop, I can use

  for i in xrange(number):

to produce

  for (i;i<number;i++)

however, if i have

  for (i = 2; an_array[i - 2] < number; i++)

how can I produce it in python?

thanks

2 Answers 2

4

You could

  1. iterate over that array and use one of the neat functions in itertools, such as takewhile():

    for item in takewhile(lambda i: i < number, array[2:]):
        # do stuff
    

    This takes values from the given iterable (here: an array) until (resp. while) its contents meet a certain condition.

    Here, item is the content of the respective array entry. If you really need the indexes, you can combine it with enumerate():

    for index, item in enumerate(takewhile(lambda i: i < number, array[2:])):
        # do stuff
    

    But this index is off by 2, because it counts the items passed through; as you start with array[2:] you'll have to add 2 in order to access the right part of the array.

  2. Use a while loop:

    i = 2
    while (array[i-2] < number):
        # do stuff
        i += 1
    
Sign up to request clarification or add additional context in comments.

1 Comment

enumerate gained a starting index value (start=0) in Python 2.6, which makes the second version a bit nicer: for index, item in enumerate(takewhile(lambda i: i < number, array[2:]), start=2):. Note that slicing the array makes a copy; if the array tends to be very large and efficiency is important you could use itertools.islice as well. But I'd probably just start with method 2, the while loop, for readability. :-)
1

You can use the following:

for i in xrange(2, number):
    # Whatever

When xrange takes 2 parameters, it creates a range from the first value to the last value. Note that the first value is included while the last value is not.

EDIT: If you're working with an array, Tim Pietzcker's method is the way to go. I just gave this method to provide a convenient counterpart.

1 Comment

What about the an_array[i - 2] < number breaking condition?

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.