def sort(nums):
for i in range(len(nums)-1,0,-1):
for j in range(i):
if nums[j]>nums[j+1]:
temp = nums[j]
nums[j] = nums[j+1]
nums[j+1] = temp
nums = [5,3,8,6,7,2] sort(nums) print(nums)
I am a beginner in python and i am learning bubble sort my question is what is the effect of putting -1 next to len(nums).
The range
takes three arguments, where the first argument is the first number in the sequence.
The first index you iterate over is the last element in the list, hence you use len(nums)-1
so you get the valid index of the last item in nums
list, as indexes are zero-based in Python.
eg
nums = [5,3,8,6,7,2]
length = len(nums) # 6
last_index = length - 1 # 5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.