What is a List?
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A list is an ordered, mutable collection of items in Python. Lists can store elements of any data type and can grow or shrink dynamically.
Creating a list and indexing
List is an ordered collection of items written in square brackets. Items keep their position, can be of any type, and can be changed after the list is created.
Define a list by enclosing comma-separated values inside square brackets [].
frameworks = ["FastAPI", "Django", "Flask"]print(frameworks[0])print(len(frameworks))Python uses 0-based indexing. frameworks[0] accesses the first item 'FastAPI'. len() returns 3.
Negative indexing: backwards access
Python provides negative indexing where -1 represents the last element, -2 the second to last, and so on.
scores = [85, 92, 78, 99]print(scores[-1])print(scores[-2])Example 1 · Reading order amounts
orders = [250, 480, 120, 960, 310]print(orders[1])print(orders[-2])print(orders[1:4])print(len(orders))480 960 [480, 120, 960] 5
What this code does
orders[1]is the second item, because counting starts at 0.orders[-2]counts from the end, so it is the second item from the right.orders[1:4]takes indexes 1, 2 and 3 and stops before 4.
Negative indexing eliminates the need to calculate len(scores) - 1 like in Java or C.
List slicing: [start:stop:step]
Slice is a part of a list taken with [start:stop:step]. It gives a new list, starts at index start, stops before index stop, and never raises an error when the range is too big.
Extract a sublist using slice notation [start:stop:step]. The stop index is always exclusive.
digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]print(digits[2:6])print(digits[::2])Example 2 · Last two days of sales
daily_sales = [1200, 1500, 900, 2100, 1800]first_three_days = daily_sales[:3]weekend_sales = daily_sales[-2:]
print(first_three_days)print(weekend_sales)[1200, 1500, 900] [2100, 1800]
What this code does
daily_sales[:3]slices elements from start up to index 2 ([1200, 1500, 900]).daily_sales[-2:]slices the last 2 elements ([2100, 1800]).
Example 3 · Stepping, reversing and over-long slices
ids = [101, 102, 103, 104, 105, 106]print(ids[::2])print(ids[::-1])print(ids[10:20])[101, 103, 105] [106, 105, 104, 103, 102, 101] []
What this code does
[::2]takes every second item from the start.[::-1]walks backwards through the whole list, so it gives a reversed copy.- A slice that starts past the end gives an empty list. It does not raise an error.
digits[2:6] extracts items from index 2 up to 5 ([2, 3, 4, 5]). digits[::2] extracts every second item.
Next step
Check your understanding
9 quick questions