How to Iterate Over Indexes in Python
The range() function requires at least one argument. Since Python indexing starts at 0, using the length of a sequence as the sole argument allows iteration over all its indices.
To get the sequence length, use the len() function. For example, you can loop through the list from previous sections, but this time by indexing its elements.
12345678# Initial list values = [1, [2, 3], 4, "code"] # Initialize a for loop over indexes for i in range(len(values)): print("Index:", i) print("Value:", values[i]) print("----") # Delimiter
At each iteration of the loop, the variable i sequentially traverses the indices of values, ranging from 0 to 3.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.
Stel mij vragen over dit onderwerp
Vat dit hoofdstuk samen
Toon voorbeelden uit de praktijk
Geweldig!
Completion tarief verbeterd naar 1.67
How to Iterate Over Indexes in Python
Veeg om het menu te tonen
The range() function requires at least one argument. Since Python indexing starts at 0, using the length of a sequence as the sole argument allows iteration over all its indices.
To get the sequence length, use the len() function. For example, you can loop through the list from previous sections, but this time by indexing its elements.
12345678# Initial list values = [1, [2, 3], 4, "code"] # Initialize a for loop over indexes for i in range(len(values)): print("Index:", i) print("Value:", values[i]) print("----") # Delimiter
At each iteration of the loop, the variable i sequentially traverses the indices of values, ranging from 0 to 3.
Bedankt voor je feedback!