Python Tutorial: Lists
Store multiple values in one variable. Lists are Python's most-used data structure.
One variable, many values
In Chapter 2 you stored one value per variable. But what if you have 100 students? 1000 products?
A list holds as many values as you need, all under one name. It is the most used data structure in Python. Twelve steps.
What you'll learn in this Python lists tutorial
This interactive Python tutorial has 10 hands-on exercises. Estimated time: 22 minutes.
- One variable, many values — Imagine you want to store five student names. Without lists, you'd do this:
- Getting items by position — Every item in a list has a position called an **index**. Python starts counting at 0:
- Changing items — Lists are **mutable** — you can change items after creating the list. Just assign to the index:
- append() and insert() — Two ways to add items:
- remove() and pop() — Two ways to remove items:
- Slicing — grab a portion — Slicing extracts a portion of a list without changing the original:
- Useful list methods — Lists come with a toolbox of built-in methods:
- in — is it there? — From Chapter 6 you know `in` works on strings. It works on lists too:
- List comprehension with a filter — Remember list comprehensions from Chapter 7? You can add a condition to filter the results:
- Build a grade tracker — Final challenge — let's build something real.
Python Lists concepts covered
- One variable, many values