For Loops Over Indices In Python
range
Here is the top part of the help for range:
class range(object)
| range([start,] stop[, step]) -> range object
|
| Returns a virtual sequence of numbersfrom start to stop by step.
The stop value is not included.
range is typically used in a for loop to iterate over a sequence of numbers. Here are some examples:
# Iterate overthe numbers 0, 1, 2, 3, and 4.
for i in range(5):
# Iterate over the numbers 2, 3, and 4.
for i in range(2, 5):
# Iterate over the numbers 3, 6, 9, 12, 15, and 18.for i in range(3, 20, 3):
Iterating over the indices of a list
Because len returns the number of items in a list, it can be used with range to iterate over all the indices. This loopprints all the values in a list:
for i in range(len(lst)):
print(lst[i])
This also gives us flexibility to process only part of a list. For example, We can print only the first half ofthe list:
for i in range(len(lst) // 2):
print(lst[i])
Or every other element:
for i in range(0, len(lst), 2):
print(lst[i])
Not "What" but "Where"
Previously, we have writtenloops over characters in a string or items in a list. However, sometimes there are problems where knowing the value of the items in a list or the characters in a string is not enough; we need to knowwhere it occurs (i.e. its index).
Example 1
The first example is described below:
def count_adjacent_repeats(s):
''' (str) -> int
Return the number of occurrences of acharacter and an adjacent character
being the same.
>>> count_adjacent_repeats('abccdeffggh')
3
'''
repeats = 0
for i in range(len(s) - 1):
if s[i]== s[i + 1]:
repeats = repeats + 1
return repeats
We want to compare a character in the string with another character in the string beside it. This is why we iterate over...
Regístrate para leer el documento completo.