Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 149 ยท Data Structures

Lists

Learn Python lists from scratch. Create lists, read items with positive and negative indexes, change them in place, understand shared references and work with nested lists.

So far, each variable you've created has held a single value: one name, one price, one temperature. Real data comes in groups: the songs in a playlist, the scores in a game, the rows of a spreadsheet. A list stores many values in one variable, in a fixed order, and lets you add, remove and change them at any time.

Lists are the workhorse of Python. You'll use them in almost every program you write, and many other data structures build on the same ideas. In this lesson you'll create lists, read items by position, change them, learn why two variables can secretly share one list, and build lists that contain other lists.

Creating a list

Write a list as values separated by commas inside square brackets:

Python Your first lists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A few things to notice:

  • A list keeps items in the order you wrote them.
  • Items can be of any type, and one list may mix types. In practice, lists usually hold items of the same kind, which makes them much easier to process in a loop.
  • Duplicates are allowed: [1, 1, 1] is a perfectly good list.
  • len() returns the number of items, and [] is an empty list with length 0.

You can also build a list from any other iterable with list():

Python
list("hey")          # ['h', 'e', 'y']
list(range(4))       # [0, 1, 2, 3]

When a list gets long, spread it over several lines. A trailing comma after the last item is allowed and makes future edits cleaner:

Python
weekdays = [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
]

Indexing: reading one item

Every item has a position called its index. Indexes start at 0, so the first item is at index 0 and the last is at len(list) - 1. Python also supports negative indexes, which count from the end: -1 is the last item, -2 the one before it, and so on.

Item "red" "orange" "yellow" "green" "blue"
Index 0 1 2 3 4
Negative index -5 -4 -3 -2 -1
Python Positive and negative indexes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reading past the end raises IndexError: list index out of range. It's one of the most common errors in Python, usually caused by forgetting that indexes start at 0. Remove the last line and run again.

To grab several items at once, such as "the first three" or "everything except the first", you use slicing, which has its own lesson: Slicing.

Lists are mutable

Unlike strings, lists are mutable: you can change them after they're created, without making a new list. Assign to an index to replace an item:

Python Changing items in place

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line fails on purpose: you can change a list's items, but not a string's characters. append() and del are just a taste. Lists come with a full toolbox of methods for adding, removing, sorting and searching, covered in List Methods.

Checking for items and looping

The in operator asks whether a value is in a list, and a for loop visits every item in order:

Python Membership and loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The built-ins sum(), max(), min() and sorted() all work on lists. sorted(nums) returns a new sorted list and leaves nums unchanged.

Lists can also be combined with operators:

  • [1, 2] + [3] creates a new list [1, 2, 3].
  • ["-"] * 3 creates ["-", "-", "-"].
  • == compares lists item by item, so [1, 2] == [1, 2] is True, while [1, 2] == [2, 1] is False.

Variables are labels, not boxes

This is the most important idea in the lesson. A variable doesn't contain a list; it refers to one. Assigning one variable to another doesn't copy the list. It makes a second label for the same list.

Python Two names, one list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Appending through alias also changed original, because both names point at the same list. .copy() (or list(original), or original[:]) creates an independent list. The is operator, covered in Membership and Identity Operators, tells you whether two names refer to the very same object.

Warning: The same sharing happens when you pass a list to a function. If the function changes the list, the caller sees the change. That's often useful, but when it isn't what you want, pass or make a copy.

Nested lists

A list can contain other lists. This is a natural way to represent grids, tables and matrices. Use one index to pick a row, then a second index to pick an item in that row:

Python A grid of seats

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

seats[1] is the second row, a list itself, and seats[1][2] is the third item in that row. Read double indexes left to right: outer list first, then inner.

The multiplication trap

It's tempting to create a grid with *, but that repeats references, not copies:

Python Why [[0] * 3] * 3 is a trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

[[0] * 3] * 3 makes one inner list and puts three references to it in the outer list, so changing one "row" changes all of them. The second version, a list comprehension, creates a fresh inner list on every iteration. Note that [0] * 3 on its own is fine, because numbers are immutable.

When to use a list

Reach for a list when you have an ordered collection that may grow, shrink or change. Python offers other structures for other needs:

  • A tuple is a fixed, unchangeable sequence, like coordinates (x, y).
  • A set holds unique items with very fast membership tests, but no order.
  • A dictionary maps keys to values, like a word to its definition.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given pets = ["cat", "dog", "fish", "bird"], what is pets[-2]?

    Negative indexes count from the end. -1 is "bird", so -2 is "fish".
  2. 2. What happens when you run nums = [1, 2, 3] and then print(nums[3])?

    Valid indexes for a 3-item list are 0, 1 and 2 (or -1 to -3). Index 3 is one past the end.
  3. 3. After a = [1, 2], b = a and b.append(3), what is a?

    b = a doesn't copy the list. Both names refer to the same list, so the change shows through a too.
  4. 4. How do you read the value 6 from grid = [[1, 2, 3], [4, 5, 6]]?

    grid[1] is the second row [4, 5, 6], and index 2 in that row is 6.
  5. 5. Which statement about lists is true?

    Lists are mutable, ordered as you insert them, allow duplicates and can mix types.

Summary

  • A list is an ordered, changeable collection written with square brackets: ["a", "b", "c"].
  • Indexes start at 0; negative indexes count from the end, with -1 as the last item. Going out of range raises IndexError.
  • Lists are mutable: assign to an index, append() items or del them in place.
  • in, len(), sum(), max(), min(), + and * all work with lists.
  • Assignment shares a list rather than copying it; use .copy() or list(x) for an independent copy.
  • Nested lists model grids: grid[row][col]. Build them with a comprehension, not [[0] * n] * m.

Next: List Methods, where you'll add, remove, sort and search list items with Python's built-in methods.