Intro to Computer Science / Unit 8: Lists and Data
8.4 Searching and Sorting
Notes
To search a list, use a loop (linear search) or the in operator.
def find(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1
print(find([7, 3, 9], 9))
- This prints
2, the index of 9. It returns -1 if the target is not found. sorted(list)returns a new sorted list.list.sort()sorts the list itself and returnsNone.- Example:
sorted([3, 1, 2])is[1, 2, 3]. Addreverse=Truefor descending order. - Sorting ideas: selection sort repeatedly picks the smallest remaining item; bubble sort swaps neighbors that are out of order.
Practice
What does
find([7, 3, 9], 5) return using the function above?5 is not in the list, so the loop finishes and the function returns -1.
What does
nums = [3, 1, 2]; nums.sort(); print(nums) display?sort() sorts the list in place.
What does
x = [3, 1, 2].sort(); print(x) display?sort() changes the list and returns None.
Ready for more? Take the Unit 8 test.