Polyglot CheatSheet - Loop

Updated: 2021-11-28

"for" Loops

C++

for (int i = 0; i < items_size; ++i) {
  cout << items[i] << endl;
}

for (int i : items) {
  cout << i << endl;
}

Mutable repeated fields

for (auto& message : *foo.mutable_values()) {
  message.set_field(true);
}

Rust

let items = [1, 2, 3];

for i in 0..items.len() {
    println!("{}", items[i]);
}

for i in &items {
    println!("{}", i);
}

Java

for (Integer k : list) {
    // ...
}
int len = list.size();
for (int i = 0; i < len; i++) {
    Integer k = list.get(i);
    // ...
}

Javascript

Use for ... in to loop through the index, and for ... of to loop through the values.

const strings = ["str1", "str2", "str3"];

for (let i in strings) {
  console.log(i);
}
// result:
// 0
// 1
// 2

for (let s of strings) {
  console.log(s);
}
// result:
// str1
// str2
// str3

Python

Loop In A Range

equivalent to Java's for (int i = 0; i < 5; i++) {}

>>> for i in range(1, 5):
...     print(i)
...
1
2
3
4

With step:

>>> for i in range(1, 10, 2):
...     print(i)
...
1
3
5
7
9

Loop In A Collection

  • for item in s: Iterate over the items of s
  • for item in sorted(s): Iterate over the items of s in order
  • for item in set(s): Iterate over unique elements of s
  • for item in reversed(s): Iterate over elements of s in reverse
  • for item in set(s).difference(t): Iterate over elements of s not in t
  • for item in random.shuffle(s): Iterate over elements of s in random order

Bash

As one-liner:

$ for i in {1..5}; do echo "$i"; done
1
2
3
4
5

"while" Loops

C++ / Java

The traditional while loop, looks the same in C++ and Java.

while (condition) {
  // ...
}

do {
  // ...
} while (condition)

Rust

loop {
  if (condition) {
    break;
  }
}