Sign in

Intro to Computer Science / Unit 8: Lists and Data

8.4 Searching and Sorting

3 practice questionsNot yet reviewed

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 returns None.
  • Example: sorted([3, 1, 2]) is [1, 2, 3]. Add reverse=True for 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?
What does nums = [3, 1, 2]; nums.sort(); print(nums) display?
What does x = [3, 1, 2].sort(); print(x) display?

Ready for more? Take the Unit 8 test.