Python & data · Lesson 08
Work with lists
Store an ordered collection, select items, and make safe changes.
- 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.
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.
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.
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.
What does topics[0] select?
Your turn
Create a list of three skills, add a fourth, and print the first two.
skills = ["Python", "SQL", "Git"] skills.append("HTML") print(skills[:2])
BUILT TOGETHER
Help make this explanation better.
Have a clearer explanation, a useful example, or a correction? Share it with the community.
Be the first to add your name when you improve this lesson.
How to get credited