PythonLesson 6 of 16
Lists in Python
A list is an ordered collection in square brackets. It fits a playlist, a shopping cart and anything else that comes in order.
Key points
- Counting starts at zero: list[0] is the first item, list[-1] the last
- list[1:3] is a slice: items 1 and 2, the end is not included
- append() adds to the end, insert() puts an item at a position, remove() deletes by value
- len() counts items, in checks whether a value is there
- sorted() returns a sorted copy and leaves the list as it was
Example
playlist = ["Intro", "Sunrise", "Run"]print(playlist[0], playlist[-1])playlist.append("Lights")playlist.insert(1, "Waves")print(playlist)print(playlist[1:3])print(len(playlist), "Run" in playlist)Waves took index 1 and pushed the others along. The slice [1:3] picked two items, because the end of a slice is left out.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Update the cart: add "eggs" at the end and take out "bread". The code below prints the cart and the number of items.
Output
What your program prints appears here.