Loop through the items in a list

The following while loop prints all the items in the list. But we’re about to see simpler ways to do the same thing.

forlist.py

monkey
rooster
dog
pig
rat
ox
tiger
hare
dragon
snake
horse
sheep

Things to try

  1. It’s simpler to use a for loop to loop through the numbers in a range. We can do this because the return value of the range function is iterable.
    for i in range(n):   #could also say range(0, n) or range(0, n, 1)
        print(animals[i])
    
    monkey
    rooster
    dog
    pig
    rat
    ox
    tiger
    hare
    dragon
    snake
    horse
    sheep
    
  2. It’s even simpler to loop through the items in the list. We can do this because a list is iterable.
    for animal in animals:
        print(animal)
    
    monkey
    rooster
    dog
    pig
    rat
    ox
    tiger
    hare
    dragon
    snake
    horse
    sheep
    
    So far, we have seen that a for loop can loop through
    1. the integers in a range
    2. the characters in a string
    3. the lines of text read from an input file in the computer. (Each line arrives as a str.)
    4. the lines of text downloaded from the Internet. (Each line arrives as sequence of bytes.)
    5. the items in a list
  3. Print the index numbers too. We could do it with the while loop:
    i = 0
    while i < n:
        print(i, animals[i])
        i += 1
    
    0 monkey
    1 rooster
    2 dog
    3 pig
    4 rat
    5 ox
    6 tiger
    7 hare
    8 dragon
    9 snake
    10 horse
    11 sheep
    
    but it’s simpler to use a for loop and a range.
    for i in range(n):
        print(i, animals[i])
    
    0 monkey
    1 rooster
    2 dog
    3 pig
    4 rat
    5 ox
    6 tiger
    7 hare
    8 dragon
    9 snake
    10 horse
    11 sheep
    
  4. We can even print the index numbers and animals without mentioning n. We saw enumerate here.
    for i, animal in enumerate(animals):
        print(i, animal)
    
    0 monkey
    1 rooster
    2 dog
    3 pig
    4 rat
    5 ox
    6 tiger
    7 hare
    8 dragon
    9 snake
    10 horse
    11 sheep
    

    Let’s align the columns and start the numbers at 1.

    for i, animal in enumerate(animals, start = 1):
        print(f"{i:2} {animal}")
    
     1 monkey
     2 rooster
     3 dog
     4 pig
     5 rat
     6 ox
     7 tiger
     8 hare
     9 dragon
    10 snake
    11 horse
    12 sheep
    
  5. Print only the first three items in the list. See Indexing.
    for animal in animals[:3]:
        print(animal)
    
    monkey
    rooster
    dog
    
    Print all but the first item in the list:
    for animal in animals[1:]:
        print(animal)
    
    rooster
    dog
    pig
    rat
    ox
    tiger
    hare
    dragon
    snake
    horse
    sheep
    
    Print the items in reverse order:
    for animal in reversed(animals):   #or for animal in animals[-1::-1]:
        print(animal)
    
    sheep
    horse
    snake
    dragon
    hare
    tiger
    ox
    rat
    pig
    dog
    rooster
    monkey
    
  6. Loop through a list of colors.
    """
    italy.py
    
    Draw the Italian flag on a tkinter Canvas widget.
    """
    
    import tkinter
    
    #Colors of the vertical bars, from left to right.
    
    colors = [
        "#008C45", #green
        "#F4F5F0", #white
        "#CD212A"  #red
    ]
    
    stripeWidth = 200       #measured in pixels
    width = len(colors) * stripeWidth
    height = width * 2 // 3 #Make sure the height is an integer.
    
    root = tkinter.Tk()
    root.title("Italian Flag")
    root.geometry(f"{width}x{height}")
    
    canvas = tkinter.Canvas(root, highlightthickness = 0)
    
    for i, color in enumerate(colors):
        canvas.create_rectangle(i * stripeWidth, 0, (i + 1) * stripeWidth,
            height, width = 0, fill = color)
    
    canvas.pack(expand = tkinter.YES, fill = "both")
    root.mainloop()
    
  7. Loop through a list of audio files:
    pip3 install playsound
    pip3 install pyobjc
    pip3 install AppKit
    
    """
    Play a list of audio files.
    """
    
    import sys
    import time
    import playsound
    
    audioFiles = [
        #puck guitar string
        "/Library/Frameworks/Python.framework/Versions/3.8" \
            "/lib/python3.8/test/audiodata/pluck-pcm24.au",
    
        #Chinese sound effect
        "http://oit2.scps.nyu.edu/~meretzkm/swift/button/chinese.mp3",
    
        #"Stand By Me"
        "http://plg208.free.fr/sauvegardes%20PC%20portable%20mes%20doc" \
            "/MUSIQUE/Ben%20E.%20King%20-%20Stand%20By%20Me.mp3",
    
        #You'll Never Walk Alone"
        "http://www.fcsongs.com/uploads/audio" \
            "/Liverpool%20FC%20-%20You%20Will%20Never%20Walk%20Alone.mp3"
    ]
    
    for audioFile in audioFiles:
        try:
            playsound.playsound(audioFile, True)
        except OSError as error:
            print(error, file = sys.stderr)
            sys.exit(1)
    
        time.sleep(1)
    
    sys.exit(0)
    
    Make it print “Now playing track 1…”, etc.
  8. Three ways to find the sum and average of the the numbers in a list of numbers.
    months = [
        31,   #January
        28,   #February
        31,   #March
        30,   #April
        31,   #May
        30,   #June
        31,   #July
        31,   #August
        30,   #September
        31,   #October
        30,   #November
        31    #December
    ]
    
    summation = 0
    
    for month in months:
        summation += month   #means summation = summation + month
    
    average = summation / len(months)
    
    print(f"A year has {summation} days.")
    print(f"The average month has {average} days (approx. {average:.4f}).")
    
    A year has 365 days.
    The average month has 30.416666666666668 days (approx. 30.4167).
    

    It’s easier to use the sum built-in function.

    months = [
        31,   #January
        28,   #February
        31,   #March
        30,   #April
        31,   #May
        30,   #June
        31,   #July
        31,   #August
        30,   #September
        31,   #October
        30,   #November
        31    #December
    ]
    
    summation = sum(months)   #or summation = functools.reduce(operator.add, months, 0)
    average = summation / len(months)
    
    print(f"A year has {summation} days.")
    print(f"The average month has {average} days (approx. {average:.4f}).")
    
    A year has 365 days.
    The average month has 30.416666666666668 days (approx. 30.4167).
    

    If all you want is the average, it’s even easier to use the mean function from the Python Standard Library.

    import statistics
    
    months = [
        31,   #January
        28,   #February
        31,   #March
        30,   #April
        31,   #May
        30,   #June
        31,   #July
        31,   #August
        30,   #September
        31,   #October
        30,   #November
        31    #December
    ]
    
    try:
        average = statistics.mean(months)
    except StatisticsError as error:
        print(error, file = sys.stderr)
        sys.exit(1)
    
    print(f"The average month has {average} days (approx. {average:.4f}).")
    
    The average month has 30.416666666666668 days (approx. 30.4167).
    
  9. Now that you’ve seen sum, could you use min to find the length of the shortest month?
    The length of the shortest month is 28 days.
    
  10. Give the whole list to print. The last two statements do the same thing.
    print(months)
    print(*months)
    print(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
    
    [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    31 28 31 30 31 30 31 31 30 31 30 31
    31 28 31 30 31 30 31 31 30 31 30 31
    
  11. Three ways to search a list:
    import sys
    
    months = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
    ]
    
    m = "June"
    
    for i, month in enumerate(months):
        if month == m:
            break
    else:
        print(f"The for loop did not find {m}.")
        sys.exit(1)
    
    print(f"The for loop found {m} at index {i}.")
    
    
    try:
        i = months.index(m)
    except ValueError as error:
        print(error)
        sys.exit(1)
    else:
        print(f"The index method found {m} at index {i}.")
    
    
    if m in months:
        print(f"{m} is a month.")
        sys.exit(0)
    else:
        print(f"{m} is not a month.")
        sys.exit(1)
    
    The for loop found June at index 5.
    The index method found June at index 5.
    June is a month.
    
  12. """
    Output the lyrics to "The Twelve Days of Christmas".
    """
    
    import sys
    
    gifts = [
        None,   #so that "partridge" is index number 1
        "partridge in a pear tree.", # 1
        "turtle doves",     # 2
        "french hens",      # 3
        "calling birds",    # 4
        "gold rings",       # 5
        "geese a-laying",   # 6
        "swans a-swimming", # 7
        "maids a-milking",  # 8
        "ladies dancing",   # 9
        "lords a-leaping",  #10
        "pipers piping",    #11
        "drummers drumming" #12
    ]
    
    n = len(gifts)
    
    for day in range(1, n):
        if day == 1:
            suffix = "st"
        elif day == 2:
            suffix = "nd"
        elif day == 3:
            suffix = "rd"
        else:
            suffix = "th"
    
        print(f"On the {day}{suffix} day of Christmas my true love gave to me")
    
        for d in range(day, 0, -1):
            if d > 1:
                prefix = d
            elif day == 1:
                prefix = "A"
            else:
                prefix = "And a"
    
            print(f"\t{prefix} {gifts[d]}")   #\t is a tab character
    
        print()
    
    sys.exit(0)
    
    On the 1st day of Christmas my true love gave to me
    	A partridge in a pear tree.
    
    On the 2nd day of Christmas my true love gave to me
    	2 turtle doves
    	And a partridge in a pear tree.
    
    On the 3rd day of Christmas my true love gave to me
    	3 french hens
    	2 turtle doves
    	And a partridge in a pear tree.
    
    On the 4th day of Christmas my true love gave to me
    	4 calling birds
    	3 french hens
    	2 turtle doves
    	And a partridge in a pear tree.
    
    On the 5th day of Christmas my true love gave to me
    	5 gold rings
    	4 calling birds
    	3 french hens
    	2 turtle doves
    	And a partridge in a pear tree.
    
    On the 6th day of Christmas my true love gave to me
    	6 geese a-laying
    	5 gold rings
    	4 calling birds
    	3 french hens
    	2 turtle doves
    	And a partridge in a pear tree.
    
    On the 7th day of Christmas my true love gave to me
    	7 swans a-swimming
    	6 geese a-laying
    	5 gold rings
    	4 calling birds
    	3 french hens
    	2 turtle doves
    	And a partridge in a pear tree.
    
    On the 8th day of Christmas my true love gave to me
    	8 maids a-milking
    	7 swans a-swimming
    	6 geese a-laying
    	5 gold rings
    	4 calling birds
    	3 french hens
    	2 turtle doves
    	And a partridge in a pear tree.
    
    On the 9th day of Christmas my true love gave to me
    	9 ladies dancing
    	8 maids a-milking
    	7 swans a-swimming
    	6 geese a-laying
    	5 gold rings
    	4 calling birds
    	3 french hens
    	2 turtle doves
    	And a partridge in a pear tree.
    
    On the 10th day of Christmas my true love gave to me
    	10 lords a-leaping
    	9 ladies dancing
    	8 maids a-milking
    	7 swans a-swimming
    	6 geese a-laying
    	5 gold rings
    	4 calling birds
    	3 french hens
    	2 turtle doves
    	And a partridge in a pear tree.
    
    On the 11th day of Christmas my true love gave to me
    	11 pipers piping
    	10 lords a-leaping
    	9 ladies dancing
    	8 maids a-milking
    	7 swans a-swimming
    	6 geese a-laying
    	5 gold rings
    	4 calling birds
    	3 french hens
    	2 turtle doves
    	And a partridge in a pear tree.
    
    On the 12th day of Christmas my true love gave to me
    	12 drummers drumming
    	11 pipers piping
    	10 lords a-leaping
    	9 ladies dancing
    	8 maids a-milking
    	7 swans a-swimming
    	6 geese a-laying
    	5 gold rings
    	4 calling birds
    	3 french hens
    	2 turtle doves
    	And a partridge in a pear tree.
    

    Now output the lyrics to Green Grow the Rushes, O.

  13. Two ways to set all the items with even indices to zero:
    mylist = [
        4,
        8,
        6,
        2,
        1,
        0,
        7,
        5,
        3,
        9
    ]
    
    n = len(mylist)
    
    for i in range(0, n, 2):
        mylist[i] = 0
    
    for i in mylist:
        print(i)
    
    0
    8
    0
    2
    0
    0
    0
    5
    0
    9
    

    n // 2 * [0]
    is a list of five 0’s.
    mylist[0::2]
    is a slice of five items in the list.

    mylist = [
        4,
        8,
        6,
        2,
        1,
        0,
        7,
        5,
        3,
        9
    ]
    
    n = len(mylist)
    mylist[0::2] = n // 2 * [0]
    
    for i in mylist:
        print(i)
    
    0
    8
    0
    2
    0
    0
    0
    5
    0
    9
    
  14. Loop through a list using a slice that has a stride.

    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

    """
    eratosthenes.py
    
    Print the prime numbers from 2 to n inclusive using the Sieve of Eratosthenes.
    l is the number of multiples of prime in the range from 2*prime to n inclusive.
    For example, there are 3 multiples of 23 in the range from 46 to 100 inclusive.
    These multiples are 46, 69, 92.
    """
    
    import sys
    
    n = 100
    
    #Begin by assuming that every integer from 2 to n inclusive is a prime number.
    #The numbers 0 and 1 are not prime numbers.
    numbers = (n + 1) * [True]
    numbers[0] = numbers[1] = False
    
    prime = 2
    
    while prime <= n:
        print(f"{prime:2}")
        l = len(numbers[2 * prime::prime])
        numbers[2 * prime::prime] = l * [False] #The multiples of prime are not prime numbers.
    
        try:
            prime = numbers.index(True, prime + 1)
        except ValueError:
            break
    
    #The surviving Trues are at the prime indices.
    print()
    print([i for i in range(n + 1) if numbers[i]])
    print(*[i for i in range(n + 1) if numbers[i]])
    
    sys.exit(0)
    
     2
     3
     5
     7
    11
    13
    17
    19
    23
    29
    31
    37
    41
    43
    47
    53
    59
    61
    67
    71
    73
    79
    83
    89
    97
    
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
    2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97