7.2. Loop for

7.2.1. Syntax

  • ITERABLE must implement iterator interface

  • More on iterators in chapter Iterators

Listing 92. for loop syntax
for <VARIABLE> in <ITERABLE> :
    ...

7.2.2. Iterating sequences

Listing 93. Iterating over str will get character on each iteration
for letter in 'setosa':
    print(letter)

# s
# e
# t
# o
# s
# a
Listing 94. Iterating over list will get one element on each iteration
DATA = [5.1, 3.5, 1.4, 0.2, 'setosa']

for obj in DATA:
    print(obj)

# 5.1
# 3.5
# 1.4
# 0.2
# 'setosa'
Listing 95. Iterating over tuple will get one element on each iteration
DATA = (5.1, 3.5, 1.4, 0.2, 'setosa')

for obj in DATA:
    print(obj)

# 5.1
# 3.5
# 1.4
# 0.2
# 'setosa'
Listing 96. Iterating over set will get one element on each iteration
DATA = {5.1, 3.5, 1.4, 0.2, 'setosa'}

for obj in DATA:
    print(obj)

# 5.1
# 3.5
# 1.4
# 0.2
# 'setosa'

7.2.3. Working with Generators and Iterators

7.2.3.1. Loops with range

  • range(start, stop, step)

  • range(0, 3) will generate (0, 1, 2)

  • start is inclusive, default: 0

  • stop is exclusive, required

  • step default: 1

Listing 97. Loops with range
for number in range(0, 3):
    print(number)

# 0
# 1
# 2
Listing 98. Loops with range
for number in range(4, 11, 2):
    print(number)

# 4
# 6
# 8
# 10

7.2.3.2. enumerate

  • Pythonic way

  • Preferred over i=0 and i+=1 for every iteration

  • enumerate() will return counter and value for every iteration

DATA = ['a', 'b', 'c']

for letter in DATA:
    print(letter)

# a
# b
# c
Listing 99. enumerate() will return counter and value for every iteration
DATA = ['a', 'b', 'c']

for i, letter in enumerate(DATA):
    print(i, letter)

# 0 a
# 1 b
# 2 c
Listing 100. enumerate() can start with custom number
DATA = ['a', 'b', 'c']

for i, letter in enumerate(DATA, start=5):
    print(i, letter)

# 5 a
# 6 b
# 7 c

7.2.4. Assignments

7.2.4.1. Example

  • Complexity level: easy

  • Lines of code to write: 6 lines

  • Estimated time of completion: 5 min

  • Solution: solution/for_counter.py

English
  1. Iterate over data from "Input" section and count occurrences of each number

  2. Create empty counter: Dict[int, int]:

    • key - digit

    • value - number of occurrences

  3. Iterating over numbers check if number is already in counter

    • If first occurrence, then add it to counter with value 1

    • If exists, then increment the value by 1

  4. Compare results with "Output" section below

Polish
  1. Iterując po danych wejściowych z sekcji "Input" policz wystąpienia każdej z cyfr

  2. Stwórz pusty counter: Dict[int, int]:

    • klucz - cyfra

    • wartość - liczba wystąpień

  3. Iterując po cyfrach sprawdź czy cyfra znajduje się już w counter

    • Jeżeli pierwsze wystąpienie, to dodaj ją do counter z wartością 1

    • Jeżeli istnieje, to zwiększ w wartość o 1

  4. Porównaj wynik z sekcją "Output" poniżej

Input
INPUT = [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]
Output
from typing import Dict

counter: Dict[int, int]
# {1: 7, 4: 8, 6: 4, 7: 4, 5: 4, 0: 7, 9: 5, 8: 6, 2: 2, 3: 3}
Solution
INPUT = [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]

counter = {}

for digit in INPUT:

    if digit not in counter:
        counter[digit] = 1
    else:
        counter[digit] += 1

print(counter)
The whys and wherefores
  • Defining dict Mapping dict

  • Updating dict

  • Iterating over sequences

7.2.4.2. Segmentation

English
  1. For input data (see below)

  2. Count occurrences of each group

  3. Define groups:

    • small - numbers in range [0-3)

    • medium - numbers in range [3-7)

    • large - numbers in range [8-9]

  4. Print counter: Dict[str, int]:

    • key - group

    • value - number of occurrences

  5. Compare results with "Output" section below

Polish
  1. Dla danych wejściowych (patrz sekcja input)

  2. Policz wystąpienia każdej z group

  3. Zdefiniuj grupy

    • small - liczby z przedziału <0-3)

    • medium - liczby z przedziału <3-7)

    • large - liczby z przedziału <7-9>

  4. Wypisz counter: Dict[str, int]:

    • klucz - grupa

    • wartość - liczba wystąpień

  5. Porównaj wynik z sekcją "Output" poniżej

Input
INPUT = [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]
Output
from typing import Dict

counter: Dict[str, int]
# {'small': 16, 'medium': 19, 'large': 15}
The whys and wherefores
  • Defining dict

  • Updating dict

  • Iterating over sequences

7.2.4.3. Text analysis

English
  1. Given is text of the "Moon Speech" by John F. Kennedy's (see below)

  2. Sentences are separated by period (.)

  3. Clean each sentence from whitespaces at the beginning and at the end

  4. Words are separated by spaces

  5. Print the total number in whole text:

    • adverbs (words ending with "ly")

    • sentences

    • words

    • letters

    • characters (including spaces inside sentences, but without periods .)

    • comas (,)

  6. Compare results with "Output" section below

Polish
  1. Dany jest tekst przemówienia "Moon Speech" wygłoszonej przez John F. Kennedy'ego (patrz sekcja input)

  2. Zdania oddzielone są kropkami (.)

  3. Każde zdanie oczyść z białych znaków na początku i końcu

  4. Słowa oddzielone są spacjami

  5. Wypisz także ile jest łącznie w całym tekście:

    • przysłówków (słów zakończonych na "ly")

    • zdań

    • słów

    • liter

    • znaków (łącznie ze spacjami wewnątrz zdań, ale bez kropek .)

    • przecinków (,)

  6. Porównaj wynik z sekcją "Output" poniżej

Input
Listing 101. "Moon Speech" by John F. Kennedy, Rice Stadium, Houston, TX, 1962-09-12 [F1]
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.
Because that goal will serve to organize and measure the best of our energies and skills.
Because that challenge is one that we are willing to accept.
One we are unwilling to postpone.
And one we intend to win
Output
Sentences: 7
Words: 71
Characters: 347
Letters: 283
Commas: 1
Adverbs: 0
The whys and wherefores
  • String splitting

  • Calculating lengths

  • Iterating over string

  • Variable naming convention

  • Good variable names