7.2. Loop for

7.2.1. Syntax

7.2.1.1. Generic syntax

  • ITERABLE must implement iterator interface

  • More on iterators in chapter Iterators

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

7.2.1.2. Example

Listing 86. for loop syntax: printing each number from list
DATA = ['a', 'b', 'c']

for letter in DATA:
    print(letter)

# a
# b
# c
Listing 87. for loop syntax: data can be inline
for letter in ['a', 'b', 'c']:
    print(letter)

# a
# b
# c

7.2.2. Iterating over str

  • Iterating str will get character on each iteration

Listing 88. Iterating over str
for letter in 'setosa':
    print(letter)

# s
# e
# t
# o
# s
# a

7.2.3. Iterating simple collections

7.2.3.1. Iterating over list

Listing 89. Iterating over list
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.2. Iterating over tuple

Listing 90. Iterating over tuple
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.3. Iterating over set

Listing 91. Iterating over set
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.4. Working with Generators and Iterators

7.2.4.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 92. Loops with range
for number in range(0, 3):
    print(number)

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

# 4
# 6
# 8
# 10

7.2.4.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 94. 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 95. 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.5. Assignments

7.2.5.1. Example

  • Complexity level: easy

  • Lines of code to write: 6 lines

  • Estimated time of completion: 5 min

  • Filename: solution/for_counter.py

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

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

    • key - digit

    • value - number of occurrences

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

    • If first occurrence, then add it to OUTPUT 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 OUTPUT: Dict[int, int]:

    • klucz - cyfra

    • wartość - liczba wystąpień

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

    • Jeżeli pierwsze wystąpienie, to dodaj ją do OUTPUT 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

OUTPUT: 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]

OUTPUT = {}

for digit in INPUT:

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

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

  • Updating dict

  • Iterating over sequences

7.2.5.2. Segmentation

English
  1. For input data (see below)

  2. Count occurrences of each group

  3. Define groups:

    • small - numbers in range [0-2]

    • medium - numbers in range [3-7]

    • large - numbers in range [8-9]

  4. Print OUTPUT: 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-2]

    • medium - liczby z przedziału [3-7]

    • large - liczby z przedziału [8-9]

  4. Wypisz OUTPUT: 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


OUTPUT: Dict[str, int]
# {'small': 16, 'medium': 23, 'large': 11}
The whys and wherefores
  • Defining dict

  • Updating dict

  • Iterating over sequences

7.2.5.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 96. "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