Pulsars
0 %
Log inSign up

Lists

Iterating over, adding to, and slicing a list

Iterating over, adding to, and slicing a list

To process each element of a list one after another, you use a for loop:

notes = [12, 15, 8, 17]
for note in notes:
    print(note)

This program displays each grade, one per line. On each pass of the loop, the variable note takes the value of the next element in the list.

To add an element to the end of a list, you use the append method:

notes = [12, 15, 8]
notes.append(17)
print(notes)   # (displays [12, 15, 8, 17])

There's also slicing, which lets you extract a portion of the list, with the syntax list[start:end] (the element at index end is not included):

notes = [12, 15, 8, 17, 9]
print(notes[1:3])   # (displays [15, 8]: the elements at index 1 and 2)
print(notes[:2])    # (displays [12, 15]: from the start up to index 2 excluded)
print(notes[2:])    # (displays [8, 17, 9]: from index 2 to the end)

A concrete example: calculating the average of a list of grades.

notes = [12, 15, 8, 17]
total = 0
for note in notes:
    total = total + note
moyenne = total / len(notes)
print(moyenne)   # (displays 13.0)

This combination (for loop, len, accumulating in a total variable) is a pattern you'll come across very often in programming.