﻿ Getting a Rogue Iteration from My .Each Loop - ITCodar

# Getting a Rogue Iteration from My .Each Loop

## Trying to iterate my function many times using i

i think you are looking for this

``sample_gamma <- function(alpha, beta, n, iter) {  mean_s = c()  mean_sd = c()  for(i in 1:iter){    a = rgamma(n, shape = alpha, scale = 1/beta)     print(c(mean(a), sd(a)))  }}``

## Modifying size of iterable during for loop - how is looping determined?

The loop executes till iterable says it has no more elements. After two cycles, the iterable has gone through two elements, and has lost two elements, which means it is at its end, and the loop terminates.

Your code is equivalent to this:

``y = [1, 2, 3, 4]i = iter(y)while True:    try:        x=next(i)    except StopIteration:        break    print(y)    print(y.pop(0))``

The list iterator holds the index that is up to be read next. In the third cycle, the list is `[3, 4]`, and `next(i)` would be needing to read `y[2]`, which is not possible, so `next` raises `StopIteration`, which ends the loop.

EDIT As to your other questions:

How do `iter` and `StopIteration`, and `__getitem__(i)` and `IndexError` factor in?

The first two are as described above: it is what defines a `for` loop. Or, if you will, it is the contract of `iter`: it will yield stuff till it stops with `StopIteration`.

The latter two, I don't think participate at all, since the list iterator is implemented in C; for example, the check for whether the iterator is exhausted directly compares the current index with `PyList_GET_SIZE`, which directly looks at `->ob_size` field; it doesn't pass through Python any more. Obviously, you could make a list iterator that would be fully in pure Python, and you'd likely be either using `len` to perform the check, or catching `IndexError` and again letting the underlying C code perform the check against `->ob_size`.

What about iterators that aren't lists?

You can define any object to be iterable. When you call `iter(obj)`, it is the same as calling `obj.__iter__()`. This is expected to return an iterator, which knows what to do with `i.__next__()` (which is what `next(i)` translates to). I believe dicts iterate (I think, haven't checked) by having an index into the list of its keys. You can make an iterator that will do anything you want, if you code it. For example:

``class AlwaysEmpty:    def __iter__(self):        return self    def __next__(self):        raise StopIterationfor x in AlwaysEmpty():    print("there was something")``

will, predictably, print nothing.

And most importantly, is this / where is this in the docs?

Iterator Types

## array.forEach running faster than native iteration? How?

There are many iteration optimizations that your `for` loop is missing such as:

• cache the array length
• iterate backwards
• use ++counter instead of counter++

These are the ones that I have heard of and used, I am sure there are more. If memory serves me correct, the backwards iterating while loop is the fastest of all looping structures (in most browsers).

See this jsperf for some examples.

Edit:
links for postfix vs prefix perf test and iterating backwards.
I was not able to find my reference for using +=1 instead of ++, so I have removed it from the list.

## GoTo Next Iteration in For Loop in java

``continue;``

`continue;` key word would start the next iteration upon invocation

For Example

``for(int i= 0 ; i < 5; i++){ if(i==2){  continue; }System.out.print(i);}``

This will print

``0134``

See

• Document

## For loop with an else and one iteration

As user2357112 mentions, and as stated in the Python docs here

a loop’s else clause runs when no break occurs

You could try something along the lines of:

``def searchContact(self, search_name):    contact_found = False    print("Your search matched the following:")    for contact in self.contacts:        if search_name in contact.name:            contact_found = True            print(contact)    if not contact_found:        print("Sorry that contact does not exist!!")``