5. Sort and search

sort() and reverse() change the list in place:

  • list.sort() orders the elements from smallest to largest and returns None.
  • list.reverse() flips the current order and returns None.

Three built-ins read information without changing the list:

  • len(list) returns how many elements the list has.
  • value in list is an operator that returns True or False.
  • list.count(value) returns how many times value appears.

Coming from JavaScript? list.sort() mutates in place and returns None; JS sort() returns the array. Use sorted(list) when you want a new list, like toSorted().

#01

Sort in place

Create numbers = [3, 1, 4, 2]. Sort the list with sort(), then print it.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Reverse in place

Create letters = ["a", "b", "c"]. Reverse the list with reverse(), then print it.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Count the elements

Create colors = ["red", "green", "blue"]. Print how many elements the list has using len().

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Check membership

Create fruits = ["apple", "banana", "cherry"]. Print whether "banana" is in the list using the in operator.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

Count occurrences

Create votes = ["yes", "no", "yes", "yes"]. Print how many times "yes" appears using count().

Print exactly:

Create a free account to save your progress and unlock chapter 2.