Beginner·6 min·basics · lists
Lists & Looping
You’ll be able to
- Create, index, and modify lists in place
- Iterate over lists with
forandenumerate() - Add and remove items with
append(),pop(),remove() - Sort lists in place and get sorted copies with
sorted()
Why this matters
Lists are the default container in every Python codebase, and for loops drive everything from ETL pipelines to ML training epochs. Understanding iteration is the difference between shipping code and copy-pasting Stack Overflow.
Common pitfalls
- Mutating a list while iterating:
for x in lst: lst.remove(x)skips elements. Iterate overlst[:]or build a new list. - Using
list = [1,2,3]as a variable name. It shadows the built-in and breakslist(range(5))later. - Assuming
a = bcopies the list. It aliases; usea = b.copy()ora = b[:]to duplicate.
A list holds an ordered sequence of values. You can loop over it directly.
Worth knowing
fruits[0]— first itemfruits.append("kiwi")— add to the end[expr for x in seq]— list comprehension; concise way to transform a list
Try it
- Add a fruit you actually like.
- Build a list of fruits whose name has more than 5 letters.
Practice
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
Progress0 / 3
- Exercise 1
Start from
fruits = ["apple", "banana", "mango"]. Append"kiwi", then print the full list. - Exercise 2
Given
nums = [4, 9, 15, 2, 7], use a loop to compute the sum and print just the total. Expected:37. - Exercise 3
From
words = ["apple", "kiwi", "banana", "fig", "mango"], build a list of just the words longer than 4 characters and print it.