Beginner level · Module 3: Working with Lists, Dictionaries and Strings · Lesson 1 of 3
Lists and List Operations
Store ordered collections and use list methods to add, remove, sort and search items.
In this lesson you will
- Add, remove and sort list items
- Use indexing, slicing and the in operator
Key concepts
indexappend/remove/sortslicingmembership test
The lesson
A list holds several values in order: items = ["rice", "sugar", "soap"]. Each item has an index starting at 0, so items[0] is the first item and items[-1] the last.
Lists can change. append() adds to the end, remove() deletes the first matching value, insert() adds at a position, and sort() puts the items in order. len(items) tells you how many there are, and the in operator checks membership: "soap" in items.
Slicing takes part of a list: items[:3] gives the first three items. Slices never cause an index error, even if the list is shorter than you expect.
Step by step
- Create an empty shopping list.
- Add three items read from input() with append().
- Remove an item after checking it is in the list.
- Sort the list and print the first three items with a slice.
Practice activity
Manage a shopping list: add items from input, remove a bought item, sort the list and print the first three items.
Expected result: A correctly updated, sorted list printed with the first three items.
Check your understanding
-
What does items[-1] return?
Show answer
The last item in the list.
-
What is the difference between list.sort() and sorted(list)?
Show answer
sort() changes the original list; sorted() returns a new sorted list and leaves the original unchanged.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.