range(len(mice))
with enumerate(mice)
8 holes.sort()
9
10 max_diff = 0
11 for i in range(len(mice)):12 if max_diff < abs(mice[i] - holes[i]):
13 max_diff = abs(mice[i] - holes[i])
14 return max_diff
range(len(sting))
with enumerate(sting)
7def permute(sting, pocket=""):
8 if len(sting) == 0:
9 print(pocket)
10 for i in range(len(sting)):11 letter = sting[i]
12 front = sting[0:i]
13 back = sting[i + 1:]
range(len(y))
with enumerate(y)
21 # iterate through columns of Y
22 for j in range(len(y[0])):
23 # iterate through rows of Y
24 for k in range(len(y)):25 result[i][j] += x[i][k] * y[k][j]
26
27
range(len(x))
with enumerate(x)
17 [0, 0]]
18
19# iterate through rows of "X"
20for i in range(len(x)):21 # iterate through columns of Y
22 for j in range(len(y[0])):
23 # iterate through rows of Y
range(len(arr))
with enumerate(arr)
12
13
14def insert_sort2(arr: list): # INSERT SORT for 2 dimensional arrays
15 for i in range(len(arr)):16 for j in range(len(arr[i])):
17 key = arr[i][j]
18 k = j - 1
Using range(len(...))
is not pythonic. Python does not have not index-based loops. Instead, it uses collection iterators.
Python has a built-in method enumerate
which adds a counter to an iterable.
Using this, you can access the counter and the value from the iterable at the same time.
It is therefore recommended to replace range(len(...))
with enumerate(...)
.
for index in range(len(mylist)):
...
for index, element in enumerate(mylist):
...