Sub topic 1
What a List Is and How to Create One
Prerequisites
You should know basic Python syntax, variables, int, str, and bool values, for loops, if statements, and how to call functions and methods.
Creating Lists
A list is an ordered, mutable collection. Ordered means each item has a position. Mutable means the list can change after creation. Lists can contain values of different types.
Create a list with square brackets:
fruits = ["apple", "banana", "cherry"]
numbers = [10, 20, 30]
empty = []
print(fruits)The order is preserved, and duplicate values are allowed.
Reading Items by Index
An index is an item's position. Python starts counting at zero, so the first item has index 0. Negative indexes count from the end.
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0]) # apple
print(fruits[-1]) # dateAn invalid index raises IndexError.
Slicing Lists
A slice reads a range and returns a new list. The stop index is excluded.
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[:2]) # ['apple', 'banana']
print(fruits[::2]) # ['apple', 'cherry']A slice has the form start:stop:step. Omitting a part uses a default value.
Lists Are Mutable
Changing a list does not create a new list automatically. Assign to an index to replace one item.
colors = ["red", "green", "blue"]
colors[1] = "yellow"
print(colors) # ['red', 'yellow', 'blue']You can also replace a range with slice assignment:
colors[0:2] = ["black", "white"]
print(colors) # ['black', 'white', 'blue']Adding Items
Use append to add one item, extend to add every item from an iterable, and insert to add an item at a position.
nums = [1, 2]
nums.append(3)
nums.extend([4, 5])
nums.insert(0, 0)
print(nums) # [0, 1, 2, 3, 4, 5]These methods change the original list and return None.
Exercise
What does items contain after items = ["a", "b"]; items.insert(1, "x")?
Show answer
["a", "x", "b"].