Arvutiteaduse instituut
  1. Kursused
  2. 2024/25 sügis
  3. Programmeerimise alused (MTAT.03.236)
EN
Logi sisse

Programmeerimise alused 2024/25 sügis

  • Home Page
  • Introduction
  • Expressions
  • Conditional Execution
  • Functions
  • Iterations
  • Strings
  • Files
  • Lists
  • Graphics?
< previousTable of Contentsnext >

8.6 LOOPING THROUGH A LIST

USING A FOR LOOP

The most straightforward method to loop through a list is using a for loop. This method allows you to access each element directly.


favorite_songs =  ["Without Me", "Valge Mersu", "Tsirkus", "Baby"]
for song in favorite_songs:
    print(song) # Prints the name of each song to the console on a new line

USING THE RANGE() FUNCTION

The range() function generates a sequence of numbers based on the value that it was passed. It’s useful when iterating over a sequence with a specific number of steps or for accessing list elements by their index.

The syntax of the range() function is as follows range(start, stop, step).

When using range() with a single argument, this specifies a sequence of numbers up until that number, meaning stop, where stop is not inclusive.


range_example= list(range(5))
print(range_example) # Outputs [0, 1, 2, 3, 4] 

If we also use start then a sequence is generated that spans from start to stop where the latter is also not inclusive.


range_example= list(range(1,5))
print(range_example) # Outputs [1, 2, 3, 4] 

Similarly to slicing, step in this case also specifies the interval between elements.



range_example = list(range(0, 10, 2))
print(range_example) # Outputs [0, 2, 4, 6, 8]

COMBINING RANGE() AND LEN() FUNCTIONS

As we’ve learned previously, len() returns the number of items in an object, such as the length of a string or a list. When combined, range(len()) we can obtain a a sequence of numbers corresponding to the indexes of a list that we can then iterate over.


numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
    numbers[i] *= 2

print(numbers) # Outputs [2, 4, 6, 8, 10]

USING ENUMERATE() TO ACCESS THE INDEX AND THE VALUE

enumerate() allows you to iterate over lists and access both the element and the index during the same iteration.


for index, song in enumerate(favorite_songs):
    print("Index is " + str(index) + " and the corresponding song is " + song)

'''
Outputs the following

Index is 0 and the corresponding song is Without Me
Index is 1 and the corresponding song is Valge Mersu
Index is 2 and the corresponding song is Tsirkus
Index is 3 and the corresponding song is Baby

'''

USING A WHILE LOOP

Although less common for list iteration, a while loop can be used to iterate through a list.


i = 0
while i < len(favorite_songs):
    print(favorite_songs[i])
    i += 1

'''
Outputs 

Without Me
Valge Mersu
Tsirkus
Baby
'''

KEY THINGS TO REMEMBER

  • Using a for loop is the simplest way to iterate over a list. It helps you access each element directly.
  • Using the range() and len() functions allows you to iterate over the indices of a list.
  • enumerate() allows you to iterate over lists and access both the element and the index during the same iteration.
  • Alternatively, you can also use a while loop to iterate over a list.
< previousTable of Contentsnext >

  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused