List basics
Understanding what are lists and how to work with them. Indexing, slicing, common methods and iterating
Lists
In the previous module we used range() to loop over sequences of numbers. But what if you need to store a collection of values, work with them, modify them, or pass them around your program? That's what lists are for.
What is a List?
A list is an ordered collection of values stored under a single variable name. You can think of it as a row of boxes — each box holds a value and has a numbered position.
Unlike C++ arrays, Python lists:
- Can store elements of mixed types (though in practice you usually keep one type)
- Have no fixed size — they grow and shrink dynamically
- Come with a rich set of built-in methods
Creating a List
Indexing
Each element has an index — its position in the list. Indices start at 0:
Negative Indices
Python also supports negative indices — they count from the end of the list:
This is very convenient — numbers[-1] always gives you the last element without needing to know the length.
Modifying Elements
You can assign a new value to any index:
Index Out of Range
Accessing an index that doesn't exist raises an IndexError:
Always make sure your index is between 0 and len(numbers) - 1.
Length of a List
len() returns the number of elements:
This is especially useful in loops:
Slicing
Slicing lets you extract a portion of a list. The syntax is list[start:stop] — returns elements from index start up to but not including stop:
Omitting Start or Stop
If you omit start, it defaults to 0. If you omit stop, it defaults to the end of the list:
Slice with Step
Just like range(), slices support a step:
numbers[::-1] is the most common Python idiom for reversing a list.
Iterating Over a List
Simple iteration — values only
This is the cleanest way when you only need the values.
Iteration with index using range(len(...))
Use this when you need the index to modify elements or reference their position.