Lists
25 min In ProgressLearning Objectives
- Create and modify lists
- Use indexing and slicing
- Apply common list methods
Creating Lists
A list is an ordered, mutable collection of items.
fruits = ["apple", "banana", "cherry"]
mixed = [1, "two", 3.0, True]
print(fruits[0]) # first item
print(fruits[-1]) # last item
List Methods
Lists have powerful built-in methods for manipulation.
animals = []
animals.append("Lion")
animals.append("Zebra")
animals.insert(1, "Elephant")
animals.remove("Zebra")
print(animals)
print(len(animals))
Slicing
Extract portions of a list with start:stop:step syntax.
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[2:5])
print(nums[:3])
print(nums[::2])
print(nums[::-1])
Course Example: List Operations
A walkthrough of common list operations from your course.
wild = ["Lion", "Zebra", "Panther", "Antelope"]
wild.append("Elephant")
animals = []
animals.extend(wild)
animals.insert(2, "Cheetah")
animals.pop(1)
animals.insert(1, "Giraffe")
animals.sort(key=None, reverse=False)
print(animals)
📝 Exercise: Shopping List Manager
Create a shopping list, add three items, remove one, sort it, and print the result.
code.py
Output