Questions tagged [loops]

Loops are a type of control flow structure in programming in which a series of statements may be executed repeatedly until some condition is met.

loops
Filter by
Sorted by
Tagged with
5694 votes
41 answers
5.3m views

Loop (for each) over an array in JavaScript

How can I loop through all the entries in an array using JavaScript?
Dante1986's user avatar
  • 59.1k
5447 votes
28 answers
4.5m views

How to access the index value in a 'for' loop?

How do I access the index while iterating over a sequence with a for loop? xs = [8, 23, 45] for x in xs: print("item #{} = {}".format(index, x)) Desired output: item #1 = 8 item #2 = ...
Joan Venge's user avatar
  • 324k
4380 votes
36 answers
1.0m views

How to enumerate an enum?

How can you enumerate an enum in C#? E.g. the following code does not compile: public enum Suit { Spades, Hearts, Clubs, Diamonds } public void EnumerateAllSuitsDemoMethod() { ...
Ian Boyd's user avatar
  • 252k
4087 votes
34 answers
7.3m views

How can I iterate over rows in a Pandas DataFrame?

I have a pandas dataframe, df: c1 c2 0 10 100 1 11 110 2 12 120 How do I iterate over the rows of this dataframe? For every row, I want to access its elements (values in cells) by the name ...
Roman's user avatar
  • 128k
4019 votes
46 answers
5.4m views

Loop through an array in JavaScript

In Java, you can use a for loop to traverse objects in an array as follows: String[] myStringArray = {"Hello", "World"}; for (String s : myStringArray) { // Do something } Can ...
Mark Szymanski's user avatar
3771 votes
7 answers
4.5m views

Iterate through a HashMap [duplicate]

What's the best way to iterate over the items in a HashMap?
burntsugar's user avatar
  • 57.8k
3584 votes
48 answers
2.8m views

How do I loop through or enumerate a JavaScript object?

I have a JavaScript object like the following: var p = { "p1": "value1", "p2": "value2", "p3": "value3" }; How do I loop ...
Tanmoy's user avatar
  • 45.1k
3305 votes
20 answers
2.4m views

How to iterate over a dictionary?

I've seen a few different ways to iterate over a dictionary in C#. Is there a standard way?
Jake Stewart's user avatar
  • 33.3k
3242 votes
45 answers
482k views

JavaScript closure inside loops – simple practical example

var funcs = []; // let's create 3 functions for (var i = 0; i < 3; i++) { // and store them in funcs funcs[i] = function() { // each should log its value. console.log("My value:", i); ...
nickf's user avatar
  • 542k
2990 votes
3 answers
258k views

Why is printing "B" dramatically slower than printing "#"?

I generated two matrices of 1000 x 1000: First Matrix: O and #. Second Matrix: O and B. Using the following code, the first matrix took 8.52 seconds to complete: Random r = new Random(); for (int i = ...
Kuba Spatny's user avatar
  • 26.8k
2370 votes
32 answers
1.6m views

Iterate through object properties

var obj = { name: "Simon", age: "20", clothing: { style: "simple", hipster: false } } for(var propt in obj){ console.log(propt + ': ' + obj[propt]); } ...
Rafay's user avatar
  • 24.1k
2280 votes
7 answers
458k views

How does PHP 'foreach' actually work?

Let me prefix this by saying that I know what foreach is, does and how to use it. This question concerns how it works under the bonnet, and I don't want any answers along the lines of "this is how you ...
DaveRandom's user avatar
  • 88.3k
2082 votes
37 answers
1.4m views

How do I break out of nested loops in Java?

I've got a nested loop construct like this: for (Type type : types) { for (Type t : types2) { if (some condition) { // Do something and break... break; // Breaks ...
boutta's user avatar
  • 24.5k
2077 votes
28 answers
1.0m views

Why is using "for...in" for array iteration a bad idea?

I've been told not to use for...in with arrays in JavaScript. Why not?
lYriCAlsSH's user avatar
  • 57.8k
1822 votes
30 answers
2.1m views

How to loop through a plain JavaScript object with the objects as members

How can I loop through all members in a JavaScript object, including values that are objects? For example, how could I loop through this (accessing the "your_name" and "your_message&...
edt's user avatar
  • 22.2k
1077 votes
28 answers
1.4m views

Traverse a list in reverse order in Python [duplicate]

How do I traverse a list in reverse order in Python? So I can start from collection[len(collection)-1] and end in collection[0]. I also want to be able to access the loop index.
Joan Venge's user avatar
  • 324k
948 votes
9 answers
528k views

A for-loop to iterate over an enum in Java

I have an enum in Java for the cardinal and intermediate directions: public enum Direction { NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST } How can I ...
Nick Meyer's user avatar
  • 39.8k
878 votes
16 answers
864k views

C# loop — break vs. continue

In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration? Example: foreach (...
Seibar's user avatar
  • 69.5k
869 votes
15 answers
1.0m views

Syntax for a single-line while loop in Bash

I am having trouble coming up with the right combination of semicolons and/or braces. I'd like to do this, but as a one-liner from the command line: while [ 1 ] do foo sleep 2 done
Brian Deacon's user avatar
  • 21.6k
854 votes
8 answers
756k views

How to break out of jQuery each loop?

How do I break out of a jQuery each loop? I have tried: return false; in the loop but this did not work. Any ideas? Update 9/5/2020 I put the return false; in the wrong place. When I put it inside ...
Luke101's user avatar
  • 64.2k
848 votes
28 answers
492k views

What is the difference between range and xrange functions in Python 2.X?

Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about for i in range(0, 20): for i in ...
Teifion's user avatar
  • 110k
717 votes
13 answers
1.3m views

Ways to iterate over a list in Java

Being somewhat new to the Java language I'm trying to familiarize myself with all the ways (or at least the non-pathological ones) that one might iterate through a list (or perhaps other collections) ...
jacobq's user avatar
  • 11.4k
698 votes
40 answers
259k views

How to iterate over a list in chunks

I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list ...
Ben Blank's user avatar
  • 55.8k
674 votes
11 answers
559k views

Calling remove in foreach loop in Java [duplicate]

In Java, is it legal to call remove on a collection when iterating through the collection using a foreach loop? For instance: List<String> names = .... for (String name : names) { // Do ...
Michael Bobick's user avatar
658 votes
14 answers
1.0m views

How to find the foreach index?

Is it possible to find the foreach index? in a for loop as follows: for ($i = 0; $i < 10; ++$i) { echo $i . ' '; } $i will give you the index. Do I have to use the for loop or is there some ...
user18334's user avatar
  • 6,673
649 votes
18 answers
420k views

Looping through array and removing items, without breaking for loop

I have the following for loop, and when I use splice() to remove an item, I then get that 'seconds' is undefined. I could check if it's undefined, but I feel there's probably a more elegant way to do ...
dzm's user avatar
  • 23.2k
648 votes
19 answers
806k views

How to iterate over a JavaScript object?

I have an object in JavaScript: { abc: '...', bca: '...', zzz: '...', xxx: '...', ccc: '...', // ... } I want to use a for loop to get its properties. And I want to iterate ...
nkuhta's user avatar
  • 10.7k
644 votes
18 answers
404k views

What's the best way to break from nested loops in JavaScript? [closed]

What's the best way to break from nested loops in Javascript? //Write the links to the page. for (var x = 0; x < Args.length; x++) { for (var Heading in Navigation.Headings) { for (var ...
Gary Willoughby's user avatar
621 votes
21 answers
772k views

PHP How to determine the first and last iteration in a foreach loop?

The question is simple. I have a foreach loop in my code: foreach($array as $element) { //code } In this loop, I want to react differently when we are in first or last iteration. How to do this?...
mehdi's user avatar
  • 9,422
612 votes
28 answers
564k views

How to remove elements from a generic list while iterating over it?

I am looking for a better pattern for working with a list of elements which each need processed and then depending on the outcome are removed from the list. You can't use .Remove(element) inside a ...
InvertedAcceleration's user avatar
612 votes
13 answers
1.2m views

How do I iterate over a JSON structure? [duplicate]

I have the following JSON structure: [{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }] How do I iterate over it using JavaScript?
Flueras Bogdan's user avatar
511 votes
15 answers
558k views

How can I avoid "RuntimeError: dictionary changed size during iteration" error?

Suppose I have a dictionary of lists: d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]} Now I want to remove key-value pairs where the values are empty lists. I tried this code: for i in d: if not d[i]...
user1530318's user avatar
  • 26.5k
510 votes
26 answers
25k views

Why does this go into an infinite loop?

I have the following code: public class Tests { public static void main(String[] args) throws Exception { int x = 0; while(x<3) { x = x++; System.out....
The Student's user avatar
508 votes
34 answers
791k views

How do I add a delay in a JavaScript loop?

I would like to add a delay/sleep inside a while loop: I tried it like this: alert('hi'); for(var start = 1; start < 10; start++) { setTimeout(function () { alert('hello'); }, 3000); } ...
olidev's user avatar
  • 20.4k
496 votes
21 answers
367k views

Is there a better way to run a command N times in bash?

I occasionally run a bash command line like this: n=0; while [[ $n -lt 10 ]]; do some_command; n=$((n+1)); done To run some_command a number of times in a row -- 10 times in this case. Often ...
bstpierre's user avatar
  • 30.6k
488 votes
10 answers
286k views

Is there a "do ... while" loop in Ruby?

I'm using this code to let the user enter in names while the program stores them in an array until they enter an empty string (they must press enter after each name): people = [] info = 'a' # must ...
Paige Ruten's user avatar
451 votes
6 answers
431k views

Iterating over all the keys of a map

Is there a way to get a list of all the keys in a Go language map? The number of elements is given by len(), but if I have a map like: m := map[string]string{ "key1":"val1", "key2":"val2" }; How do ...
Martin Redmond's user avatar
449 votes
1 answer
14k views

Scalaz iteratees: "Lifting" `EnumeratorT` to match `IterateeT` for a "bigger" monad

If I have an EnumeratorT and a corresponding IterateeT I can run them together: val en: EnumeratorT[String, Task] = EnumeratorT.enumList(List("a", "b", "c")) val it: IterateeT[String, Task, Int] = ...
lmm's user avatar
  • 17.4k
438 votes
8 answers
595k views

Breaking out of nested loops [duplicate]

Is there an easier way to break out of nested loops than throwing an exception? (In Perl, you can give labels to each loop and at least continue an outer loop.) for x in range(10): for y in range(...
Michael Kuhn's user avatar
  • 8,672
437 votes
5 answers
202k views

do { ... } while (0) — what is it good for? [duplicate]

I've been seeing that expression for over 10 years now. I've been trying to think what it's good for. Since I see it mostly in #defines, I assume it's good for inner scope variable declaration and for ...
gilm's user avatar
  • 7,880
422 votes
29 answers
575k views

How to retry after exception?

I have a loop starting with for i in range(0, 100). Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will continue in the ...
FurtiveFelon's user avatar
405 votes
12 answers
666k views

What is the "right" way to iterate through an array in Ruby?

PHP, for all its warts, is pretty good on this count. There's no difference between an array and a hash (maybe I'm naive, but this seems obviously right to me), and to iterate through either you just ...
Tom Lehman's user avatar
  • 87.7k
400 votes
13 answers
730k views

Pythonic way to combine for-loop and if-statement

I know how to use both for loops and if statements on separate lines, such as: >>> a = [2,3,4,5,6,7,8,9,0] ... xyz = [0,12,4,6,242,7,9] ... for x in xyz: ... if x in a: ... print(...
ChewyChunks's user avatar
  • 4,609
398 votes
9 answers
262k views

Declaring variables inside loops, good practice or bad practice?

Question #1: Is declaring a variable inside a loop a good practice or bad practice? I've read the other threads about whether or not there is a performance issue (most said no), and that you should ...
JeramyRR's user avatar
  • 4,363
386 votes
18 answers
517k views

Loop backwards using indices

I am trying to loop from 100 to 0. How do I do this in Python? for i in range (100,0) doesn't work. For discussion of why range works the way it does, see Why are slice and range upper-bound ...
Joan Venge's user avatar
  • 324k
385 votes
8 answers
502k views

How do I skip an iteration of a `foreach` loop?

In Perl I can skip a foreach (or any loop) iteration with a next; command. Is there a way to skip over an iteration and jump to the next loop in C#? foreach (int number in numbers) { if (...
Brian's user avatar
  • 8,217
381 votes
2 answers
230k views

In Ruby, how do I skip a loop in a .each loop, similar to 'continue' [duplicate]

In Ruby, how do I skip a loop in a .each loop, similar to continue in other languages?
Blankman's user avatar
  • 264k
380 votes
13 answers
284k views

Is there a difference between "pass" and "continue" in a for loop in Python?

Is there any significant difference between the two Python keywords continue and pass like in the examples for element in some_list: if not element: pass and for element in some_list: ...
Aufwind's user avatar
  • 25.8k
377 votes
13 answers
197k views

Is recursion ever faster than looping?

I know that recursion is sometimes a lot cleaner than looping, and I'm not asking anything about when I should use recursion over iteration, I know there are lots of questions about that already. ...
Carson Myers's user avatar
  • 38.1k
366 votes
16 answers
1.3m views

Batch script loop

I need to execute a command 100-200 times, and so far my research indicates that I would either have to copy/paste 100 copies of this command, OR use a for loop, but the for loop expects a list of ...
Tom J Nowell's user avatar
  • 9,821

1
2 3 4 5
1929