Course contentsLesson 8 of 13← Course overview
  1. 01Meet Python12 min
  2. 02Set up and run Python12 min
  3. 03Variables and data types15 min
  4. 04Strings and input15 min
  5. 05Decisions with conditionals15 min
  6. 06Repeat work with loops15 min
  7. 07Functions and return values18 min
  8. 08Work with lists16 min
  9. 09Dictionaries and tuples16 min
  10. 10Understand errors and exceptions14 min
  11. 11Read and write files16 min
  12. 12Modules and the standard library14 min
  13. 13Build a small data summary20 min

Python & data · Lesson 08

Work with lists

Edit lesson

Store an ordered collection, select items, and make safe changes.

16 minProgress saves on this device
In this lesson
  • Create and index lists
  • Add and remove items
  • Use a slice and understand a shallow copy

Helpful background: Understand variables and loops.

Create and access a list

A list is an ordered, mutable collection. Use square brackets to create one and zero-based indexes to access its items. A negative index counts from the end.

Accessing an index that does not exist raises IndexError. Check the length when the list may be empty.

Read itemspython
topics = ["Python", "SQL", "Git"]
print(topics[0])   # Python
print(topics[-1])  # Git
print(len(topics))

Change a list

append() adds one item to the end. remove() removes the first equal value and raises ValueError if it is absent. pop() removes and returns an item at an index.

These methods modify the existing list; append() does not return the updated list.

Update itemspython
topics = ["Python", "SQL"]
topics.append("Git")
topics.remove("SQL")
print(topics)  # ['Python', 'Git']

Take a slice

A slice uses a start and an excluded stop position. topics[0:2] contains the first two elements. A full slice topics[:] creates a new, shallow list.

A shallow copy contains references to the same nested objects. Simply assigning another name to the original list does not create a copy.

Copy a listpython
topics = ["Python", "SQL", "Git"]
first_two = topics[:2]
copy = topics[:]
copy.append("HTML")
print(first_two)
print(topics)

Iterate over items

Use a for loop to inspect each item. Avoid changing the size of the same list while iterating over it; create a new list or iterate over a copy when appropriate.

Knowledge check

What does topics[0] select?

Try first; feedback appears after you check.
Apply it

Your turn

Create a list of three skills, add a fourth, and print the first two.

Continue readingPython: lists

BUILT TOGETHER

Help make this explanation better.

Have a clearer explanation, a useful example, or a correction? Share it with the community.

Contributors

Be the first to add your name when you improve this lesson.

How to get credited
Previous lessonNext lesson