range(len(arr))
with enumerate(arr)
12 # Find the minimum element in remaining
13 # unsorted array
14 min_idx = i
15 for j in range(i + 1, len(arr)):16 if arr[min_idx] > arr[j]:
17 min_idx = j
18
range(len(arr))
with enumerate(arr)
8# Function to do selection sort
9def selection_sort(arr: List[T]) -> None:
10 # Traverse through all array elements
11 for i in range(len(arr)):12 # Find the minimum element in remaining
13 # unsorted array
14 min_idx = i
range(len(arr))
with enumerate(arr)
34 # Copying the output array to arr[],
35 # so that arr now contains sorted numbers
36 i = 0
37 for i in range(0, len(arr)):38 arr[i] = output[i]
39
40
range(len(arr))
with enumerate(arr)
2"""
3def insertion_sort(arr):
4 # Traverse through 1 to len(arr)
5 for i in range(1, len(arr)): 6 key = arr[i]
7
8 # Move elements of arr[0..i-1], that are
range(len(array))
with enumerate(array)
29
30 # Find where to put the item.
31 pos = cycleStart
32 for i in range(cycleStart + 1, len(array)):33 if array[i] < item:
34 pos += 1
35
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):
...