Python for beginners · Lesson 7 of 15
Lists: keep many values together
Create lists, read items by index, add, change and remove items, sort them and use sum(), min(), max() and len() on them.
A list holds several values in one variable, in order. You write it with square brackets and commas between the items. Lists can hold strings, numbers or a mix, and they can grow and shrink while the program runs.
fruits = ["apple", "banana", "cherry"]
print(fruits)
print(len(fruits))
print(fruits[0])
print(fruits[-1])
print(fruits[0:2])['apple', 'banana', 'cherry'] 3 apple cherry ['apple', 'banana']
Indexes and slices work just like with strings: the first item is at index 0.
Changing a list
Unlike strings, lists can be changed in place. list.append() adds an item at the end, list.insert() puts one at a given position, list[i] = value replaces an item, list.remove() deletes the first item with that value and list.pop() takes out the last item and gives it back to you.
shopping = ["milk", "bread"]
shopping.append("eggs")
print(shopping)
shopping.insert(0, "coffee")
print(shopping)
shopping[2] = "rye bread"
print(shopping)
shopping.remove("milk")
print(shopping)
last = shopping.pop()
print(last)
print(shopping)['milk', 'bread', 'eggs'] ['coffee', 'milk', 'bread', 'eggs'] ['coffee', 'milk', 'rye bread', 'eggs'] ['coffee', 'rye bread', 'eggs'] eggs ['coffee', 'rye bread']
remove() stops the program with a ValueError when the item is not in the list. Check first with in: if "tea" in shopping: shopping.remove("tea").Lists of numbers
sum(), min() and max() work on a whole list at once. sorted() gives you a new sorted list and leaves the original alone, while the method list.sort() sorts the list itself.
prices = [4.5, 12.0, 3.25, 8.0]
print(sum(prices))
print(min(prices), max(prices))
print(round(sum(prices) / len(prices), 2))
print(sorted(prices))
print(prices)
prices.sort(reverse=True)
print(prices)27.75 3.25 12.0 6.94 [3.25, 4.5, 8.0, 12.0] [4.5, 12.0, 3.25, 8.0] [12.0, 8.0, 4.5, 3.25]
From text to a list and back
str.split() cuts a string into a list of strings, and str.join() glues a list of strings back into one string, with the separator you choose. Use in to check whether a value is in a list, and list.index() to find its position.
cities = "Paris,Rome,Oslo,Lima".split(",")
print(cities)
print("Rome" in cities)
print("Berlin" in cities)
print(cities.index("Oslo"))
print(" / ".join(cities))['Paris', 'Rome', 'Oslo', 'Lima'] True False 2 Paris / Rome / Oslo / Lima
sorted() and list.sort() sort strings alphabetically, with capital letters before lower-case ones. Add reverse=True to sort from largest to smallest.✎ Exercise
Start with the playlist below. Add "Song D" at the end, remove "Song B", put "Intro" at the very beginning, then print the list, and on the next line how many songs it has followed by the word songs.
Hint: You need append(), remove(), insert(0, ...) and len().
playlist = ["Song A", "Song B", "Song C"]
# your code here
Expected output:
['Intro', 'Song A', 'Song C', 'Song D'] 4 songs
Show a solution
playlist = ["Song A", "Song B", "Song C"]
playlist.append("Song D")
playlist.remove("Song B")
playlist.insert(0, "Intro")
print(playlist)
print(len(playlist), "songs")['Intro', 'Song A', 'Song C', 'Song D'] 4 songs
Check yourself
1. What is the index of the first item in a list?
Python counts positions from 0, so the first item is items[0].
2. After nums = [3, 1, 2] and new = sorted(nums), what is nums?
sorted() returns a new list and does not change the original. Only nums.sort() changes nums.
3. Which method adds an item to the end of a list?
append() adds at the end. insert() needs a position, and lists have no add() method.