12.2. Loop For

12.2.1. Rationale

>>> data = ['a', 'b', 'c']
>>> i = 0
>>>
>>> while i < len(data):
...     x = data[i]
...     print(x)
...     i += 1
a
b
c
>>> data = ['a', 'b', 'c']
>>>
>>> for x in data:
...     print(x)
a
b
c

12.2.2. Syntax

  • ITERABLE must implement iterator interface

  • More information in Protocol Iterator

For loop syntax:

for <variable> in <iterable>:
    <do something>
>>> for digit in [1, 2, 3]:
...     pass

12.2.3. Convention

  • The longer the loop scope, the longer the variable name should be

  • Avoid one letters if scope is longer than one line

  • Prefer locally meaningful name over generic names

  • Generic names:

    • obj - generic name (in Python everything is an object)

    • element - generic name

    • item - generic name

    • x - ok for oneliners, bad for more than one line

    • e - ok for oneliners, bad for more than one line

    • l - bad

    • o - bad

    • d - bad (for digit)

  • Locally meaningful name:

    • letter

    • feature

    • digit

    • person

    • color

    • username

    • etc.

  • Special meaning (by convention):

    • i - for loop counter

    • _ - if value is not used

>>> for x in [1, 2, 3]:
...     print(x)
1
2
3
>>> for i in range(0,3):
...     print(i)
0
1
2
>>> for _ in range(3):
...     spawn_thread()

12.2.4. Iterating Sequences

  • Iterating works for builtin sequences:

    • str

    • bytes

    • list

    • tuple

    • set

    • frozenset

    • dict

>>> DATA = 'NASA'
>>>
>>> for letter in DATA:
...     print(letter)
N
A
S
A
>>> DATA = [1, 2, 3]
>>>
>>> for digit in DATA:
...     print(digit)
1
2
3
>>> DATA = ['a', 'b', 'c']
>>>
>>> for letter in DATA:
...     print(letter)
a
b
c
>>> CREW = ['Mark Watney', 'Melissa Lewis', 'Rick Martinez']
>>>
>>> for astronaut in CREW:
...     print(astronaut)
Mark Watney
Melissa Lewis
Rick Martinez
>>> DATA = [5.1, 3.5, 1.4, 0.2, 'setosa']
>>>
>>> for value in DATA:
...     print(value)
5.1
3.5
1.4
0.2
setosa

12.2.5. Range

  • range(start, stop, step)

  • start is inclusive, default: 0

  • stop is exclusive, required

  • step default: 1

>>> range(0, 5)
range(0, 5)
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(0, 5))
[0, 1, 2, 3, 4]
>>> list(range(0, 5, 1))
[0, 1, 2, 3, 4]
>>> list(range(0, 5, 2))
[0, 2, 4]

Loops with range:

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

Loops with range:

>>> for number in range(4, 11, 2):
...     print(number)
4
6
8
10

12.2.6. Note to the Programmers of Other Languages

There are several types of loops in general:

  • for

  • foreach

  • while

  • do while

  • until

But in Python we have only two:

  • while

  • for

This does not takes into consideration comprehensions and generator expressions, which will be covered in next chapters.

Note, that Python for is not the same as for in other languages, such as C, C++, C#, JAVA, Java Script. Python for loop is more like foreach. Check the following example in JAVA:

char[] DATA = {'a', 'b', 'c'};

forEach (var letter : DATA) {
    System.out.println(letter);
}

And this relates to Python regular for loop:

>>> DATA = ['a', 'b', 'c']
>>>
>>> for letter in DATA:
...     print(letter)
a
b
c

Regular for loop in other languages looks like that (example in C++):

char DATA[] = {'a', 'b', 'c'}

for (int i = 0; i < std::size(DATA); i++) {
   letter = data[i];
   printf(letter);
}

Python equivalent will be:

>>> DATA = ['a', 'b', 'c']
>>> i = 0
>>>
>>> while i < len(DATA):
...     letter = DATA[i]
...     print(letter)
...     i += 1
a
b
c

Yes, that's true, it is a while loop. This is due to the fact, that for loop from other languages is more like a while loop in Python.

Nevertheless, the very common bad practice is to do range(len()):

>>> data = ['a', 'b', 'c']
>>>
>>> for i in range(len(data)):
...     letter = data[i]
...     print(letter)
a
b
c

Note, how similar are those concepts. This is trying to take syntax from other languages and apply it to Python. range(len()) is considered a bad practice and it will not work with generators. But it gives similar look-and-feel.

Please remember:

  • Python for is more like foreach in other languages.

  • Python while is more like for in other languages.

12.2.7. Assignments

Code 12.7. Solution
"""
* Assignment: Loop For Count
* Required: yes
* Complexity: easy
* Lines of code: 7 lines
* Time: 5 min

English:
    1. Count occurrences of each color
    2. Run doctests - all must succeed

Polish:
    1. Zlicz wystąpienia każdego z kolorów
    2. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> type(red)
    <class 'int'>
    >>> type(green)
    <class 'int'>
    >>> type(blue)
    <class 'int'>
    >>> red
    3
    >>> green
    2
    >>> blue
    2
"""

DATA = ['red', 'green', 'blue', 'red', 'green', 'red', 'blue']

# int: number of 'red' elements in DATA
red = ...

# int: number of 'green' elements in DATA
green = ...

# int: number of 'blue' elements in DATA
blue = ...

Code 12.8. Solution
"""
* Assignment: Loop For Counter
* Required: yes
* Complexity: easy
* Lines of code: 5 lines
* Time: 5 min

English:
    1. Iterate over `DATA`
    2. Count occurrences of each number
    3. Create empty `result: dict[int, int]`:
        a. key - digit
        b. value - number of occurrences
    4. Iterating over numbers check if number is already in `result`
        a. If first occurrence, then add it to `result` with value 1
        b. If exists, then increment the value by 1
    5. Run doctests - all must succeed

Polish:
    1. Iteruj po `DATA`
    2. Policz wystąpienia każdej z cyfr
    3. Stwórz pusty `result: dict[int, int]`:
        a. klucz - cyfra
        b. wartość - liczba wystąpień
    4. Iterując po cyfrach sprawdź czy cyfra znajduje się już w `result`
        a. Jeżeli pierwsze wystąpienie, to dodaj ją do `result` z wartością 1
        b. Jeżeli istnieje, to zwiększ w wartość o 1
    5. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> assert type(result) is dict
    >>> assert all(type(x) is int for x in result.keys())
    >>> assert all(type(x) is int for x in result.values())
    >>> assert all(x in result.keys() for x in range(0, 10))

    >>> result
    {1: 7, 4: 8, 6: 4, 7: 4, 5: 4, 0: 7, 9: 5, 8: 6, 2: 2, 3: 3}
"""

DATA = [1, 4, 6, 7, 4, 4, 4, 5, 1, 7, 0,
        0, 6, 5, 0, 0, 9, 7, 0, 4, 4, 8,
        2, 4, 0, 0, 1, 9, 1, 7, 8, 8, 9,
        1, 3, 5, 6, 8, 2, 8, 1, 3, 9, 5,
        4, 8, 1, 9, 6, 3]

# dict[int,int]: number of occurrences of each digit from DATA
result = ...

Code 12.9. Solution
"""
* Assignment: Loop For Segmentation
* Required: yes
* Complexity: easy
* Lines of code: 10 lines
* Time: 8 min

English:
    1. Count occurrences of each group
    2. Define groups:
        a. `small` - numbers in range [0-3)
        b. `medium` - numbers in range [3-7)
        c. `large` - numbers in range [7-10)
    3. Print `result: dict[str, int]`:
        a. key - group
        b. value - number of occurrences
    4. Run doctests - all must succeed

Polish:
    1. Policz wystąpienia każdej z group
    2. Zdefiniuj grupy
        a. `small` - liczby z przedziału <0-3)
        b. `medium` - liczby z przedziału <3-7)
        c. `large` - liczby z przedziału <7-10)
    3. Wypisz `result: dict[str, int]`:
        a. klucz - grupa
        b. wartość - liczba wystąpień
    4. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> type(result)
    <class 'dict'>

    >>> assert all(type(x) is str for x in result.keys())
    >>> assert all(type(x) is int for x in result.values())

    >>> result
    {'small': 16, 'medium': 19, 'large': 15}
"""

DATA = [1, 4, 6, 7, 4, 4, 4, 5, 1, 7, 0,
        0, 6, 5, 0, 0, 9, 7, 0, 4, 4, 8,
        2, 4, 0, 0, 1, 9, 1, 7, 8, 8, 9,
        1, 3, 5, 6, 8, 2, 8, 1, 3, 9, 5,
        4, 8, 1, 9, 6, 3]

# dict[str,int] number of digit occurrences in segments
result = {'small': 0, 'medium': 0, 'large': 0}

Code 12.10. Solution
"""
* Assignment: Loop For Newline
* Required: yes
* Complexity: easy
* Lines of code: 2 lines
* Time: 5 min

English:
    1. Define `result: str`
    2. Use `for` to iterate over `DATA`
    3. Join lines of text with newline (`\n`) character
    4. Do not use `str.join()`
    5. Run doctests - all must succeed

Polish:
    1. Zdefiniuj `result: str`
    2. Użyj `for` do iterowania po `DATA`
    3. Połącz linie tekstu znakiem końca linii (`\n`)
    4. Nie używaj `str.join()`
    5. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> assert type(result) is str

    >>> result.count('\\n')
    3

    >>> result  # doctest: +NORMALIZE_WHITESPACE
    'We choose to go to the Moon.\\nWe choose to go to the Moon in this decade
    and do the other things.\\nNot because they are easy, but because they are
    hard.\\n'
"""

DATA = [
    'We choose to go to the Moon.',
    'We choose to go to the Moon in this decade and do the other things.',
    'Not because they are easy, but because they are hard.',
]

# str: DATA joined with newline - \n
result = ...

Code 12.11. Solution
"""
* Assignment: Loop For Translate
* Required: yes
* Complexity: easy
* Lines of code: 2 lines
* Time: 5 min

English:
    1. Define `result: str`
    2. Use `for` to iterate over `DATA`
    3. If letter is in `PL` then use conversion value as letter
    4. Add letter to `result`
    5. Run doctests - all must succeed

Polish:
    1. Zdefiniuj `result: list`
    2. Użyj `for` do iteracji po `DATA`
    3. Jeżeli litera jest w `PL` to użyj przekonwertowanej wartości jako litera
    4. Dodaj literę do `result`
    5. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> type(result)
    <class 'str'>

    >>> result
    'zazolc gesla jazn'
"""

PL = {'ą': 'a', 'ć': 'c', 'ę': 'e',
      'ł': 'l', 'ń': 'n', 'ó': 'o',
      'ś': 's', 'ż': 'z', 'ź': 'z'}

DATA = 'zażółć gęślą jaźń'

# str: DATA with substituted PL diacritic chars to ASCII letters
result = ...

Code 12.12. Solution
"""
* Assignment: Loop For Months
* Required: yes
* Complexity: easy
* Lines of code: 4 lines
* Time: 5 min

English:
    1. Convert `MONTH` into `result: dict[int,str]`:
        a. Keys: month number
        b. Values: month name
    2. Do not use `enumerate`
    3. Run doctests - all must succeed

Polish:
    1. Przekonwertuj `MONTH` w `result: dict[int,str]`:
        a. klucz: numer miesiąca
        b. wartość: nazwa miesiąca
    2. Nie używaj `enumerate`
    3. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> type(result)
    <class 'dict'>

    >>> assert all(type(x) is int for x in result.keys())
    >>> assert all(type(x) is str for x in result.values())
    >>> assert all(x in result.keys() for x in range(1, 13))
    >>> assert all(x in result.values() for x in MONTHS)

    >>> 13 not in result
    True
    >>> 0 not in result
    True

    >>> result  # doctest: +NORMALIZE_WHITESPACE
    {1: 'January',
     2: 'February',
     3: 'March',
     4: 'April',
     5: 'May',
     6: 'June',
     7: 'July',
     8: 'August',
     9: 'September',
     10: 'October',
     11: 'November',
     12: 'December'}
"""

MONTHS = ['January', 'February', 'March', 'April',
          'May', 'June', 'July', 'August', 'September',
          'October', 'November', 'December']

# dict[int,str]: dict with month number and name. Start with 1
result = ...