← Intro to programming with Python

Lists: many values in one variable

Make a list, read items by index, and change it.

Start this lesson

A list holds many values in order, inside square brackets, separated by commas. Instead of ten variables for ten songs, you keep one playlist. Items are numbered from 0, exactly like characters in a string, so playlist[0] is the first song. Unlike strings, lists can be changed: append() adds to the end, remove() takes out a value, sort() puts them in order, and len() tells you how many there are.

playlist = ["Calm", "Sunrise", "Drift"]
print(playlist[0])        # Calm
playlist.append("Echo")   # add to the end
playlist.remove("Sunrise")
playlist[0] = "Calm (live)"
playlist.sort()
print(playlist)
print(len(playlist))      # 3

After the changes, the sorted list is ['Calm (live)', 'Drift', 'Echo']. playlist[0] = ... replaces one item.

Common mistake: writing playlist = playlist.sort(). sort() changes the list in place and gives back None, so the list is lost. Just write playlist.sort().

remove() takes out the first matching VALUE. If the value is not there, you get a ValueError. Check with if "Echo" in playlist: first.

Asking for an index past the end, like playlist[10], gives an IndexError.