5. Sort and search
sort() and reverse() change the list in place:
list.sort()orders the elements from smallest to largest and returnsNone.list.reverse()flips the current order and returnsNone.
Three built-ins read information without changing the list:
len(list)returns how many elements the list has.value in listis an operator that returnsTrueorFalse.list.count(value)returns how many timesvalueappears.
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().
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.
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.
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.
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.
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.