Polyglot CheatSheet - Loop

Updated: 2018-06-26

Bash

As one-liner:

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

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

Java

List<Integer> list;

// A
for (Integer k : list) {
    ...
}

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

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

B: list.size() will be calculated in each iteration

A vs C: if list is ArrayList, they are the same, each iteration O(1); if LinkedList list.get(i) will take O(N);