Lesson 11 · 11 of 20
Working with lists · Python
Add, remove and sort the items of a Python list with append, insert, remove, pop and sort, and take parts of it with slicing [a:b].

Lists have methods: functions written after a dot that work on that list. append("apples") adds at the end and insert(0, "coffee") adds at the given position, here the very first.
remove("bread") removes the first item with that value. pop() removes the last item and also returns it, so you can keep it: last is apples.
sort() puts the list in order from smallest to largest and changes it in place (it does not make a new one). With sort(reverse=True) it goes from largest to smallest: best scores first.
Slicing takes a part: scores[1:4] goes from position 1 to 3 (the end is left out). Leave out the start or the end and it runs to the edge: scores[:3] are the first three and scores[3:] the rest. scores[::-1] gives it backwards.
index(88) looks for a value and tells you its position: 1, because after sorting from best to worst, 88 is the second one.
Code · main.py
# A shopping list that grows and shrinks.shopping = ["milk", "bread", "eggs"]shopping.append("apples") # add at the endshopping.insert(0, "coffee") # add at a positionprint("After adding:", shopping)shopping.remove("bread") # remove by valuelast = shopping.pop() # remove the last one and return itprint("Removed:", last)print("Now:", shopping)# sort() puts the list in order (it changes the list itself).scores = [72, 95, 58, 88, 64]scores.sort()print("Sorted:", scores)scores.sort(reverse=True)print("Best first:", scores)# Slicing: list[start:stop] takes a part (stop is not included).print("Top 3:", scores[:3])print("The rest:", scores[3:])print("Middle:", scores[1:4])print("Backwards:", scores[::-1])print("Position of 88:", scores.index(88))Output · python3 main.py
After adding: ['coffee', 'milk', 'bread', 'eggs', 'apples'] Removed: apples Now: ['coffee', 'milk', 'eggs'] Sorted: [58, 64, 72, 88, 95] Best first: [95, 88, 72, 64, 58] Top 3: [95, 88, 72] The rest: [64, 58] Middle: [88, 72, 64] Backwards: [58, 64, 72, 88, 95] Position of 88: 1
Key points
append()adds at the end;insert(i, x)at positioni.remove(x)removes by value;pop()removes the last one and returns it.sort()sorts;sort(reverse=True)the other way round.items[a:b]goes fromatob - 1;items[::-1]reverses.
Exercise
Add a 100 and a 47 to the scores, sort the list, then print the two worst scores with a slice and the median (the middle item).