Imagine you need to store the marks of 60 students. Creating 60 separate variables like marks1, marks2, marks3... would be a nightmare.
Instead, Python lets you store all of them in one variable using a list. Lists are probably the data structure you'll use most often in Python.
What is a List?
A list is an ordered, changeable (mutable) collection of items, written inside square brackets and separated by commas.
marks = [85, 92, 78, 64, 99]
fruits = ["apple", "banana", "mango"]
print(marks)
print(fruits)
print(type(marks))Output:
[85, 92, 78, 64, 99]
['apple', 'banana', 'mango']
<class 'list'>Key properties of a list:
Ordered: items keep the order in which you put them.
Mutable: you can change, add, and remove items after creating the list.
Allows duplicates: the same value can appear more than once.
Can hold any type: numbers, strings, booleans, even other lists.
Creating Lists
empty = []
mixed = [101, "Riya", 8.9, True]
repeated = [0, 0, 1, 1]
from_range = list(range(1, 6))
from_string = list("hello")
print(empty)
print(mixed)
print(repeated)
print(from_range)
print(from_string)Output:
[]
[101, 'Riya', 8.9, True]
[0, 0, 1, 1]
[1, 2, 3, 4, 5]
['h', 'e', 'l', 'l', 'o']The list() function converts any iterable (something you can loop over, like a range or a string) into a list.
Length of a List
fruits = ["apple", "banana", "mango"]
print(len(fruits))
print(len([]))Output:
3
0Accessing Items: Indexing
List indexing works exactly like string indexing, which you learned in String Indexing & Slicing. Indexes start at 0, and negative indexes count from the end:
fruits = ["apple", "banana", "mango", "grapes"]
index: 0 1 2 3
negative: -4 -3 -2 -1fruits = ["apple", "banana", "mango", "grapes"]
print(fruits[0])
print(fruits[2])
print(fruits[-1])
print(fruits[-2])Output:
apple
mango
grapes
mangoUsing an index that doesn't exist raises an error:
fruits = ["apple", "banana", "mango", "grapes"]
print(fruits[4])Output:
IndexError: list index out of rangeFor a list of length n, valid indexes are 0 to n - 1 (or -n to -1).
Slicing Lists
Slicing also works the same way as with strings: list[start:stop:step], where stop is not included. A slice always returns a new list.
nums = [10, 20, 30, 40, 50, 60]
print(nums[1:4])
print(nums[:3])
print(nums[3:])
print(nums[::2])
print(nums[::-1])Output:
[20, 30, 40]
[10, 20, 30]
[40, 50, 60]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]Unlike indexing, slicing never raises an IndexError. nums[4:100] simply gives [50, 60].
Lists Are Mutable
This is the big difference between lists and strings. You cannot change a character inside a string, but you can change an item inside a list:
fruits = ["apple", "banana", "mango"]
fruits[1] = "kiwi"
print(fruits)Output:
['apple', 'kiwi', 'mango']Trying the same with a string fails:
name = "python"
name[0] = "P"Output:
TypeError: 'str' object does not support item assignmentChanging a Range of Items
You can also assign to a slice. The new items replace the old ones, and the list can even grow or shrink:
nums = [1, 2, 3, 4, 5]
nums[1:3] = [20, 30]
print(nums)
nums[1:3] = [7, 8, 9]
print(nums)Output:
[1, 20, 30, 4, 5]
[1, 7, 8, 9, 4, 5]Deleting Items with del
nums = [10, 20, 30, 40, 50]
del nums[0]
print(nums)
del nums[1:3]
print(nums)Output:
[20, 30, 40, 50]
[20, 50]Lists also have many built-in methods to add, remove, search and sort items, such as append(), insert(), remove(), pop() and sort(). We'll cover them all in the next chapter, List Methods in Python.
Looping Through a List
Directly over the items
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)Output:
apple
banana
mangoUsing indexes with range(len())
Use this when you need the position, for example to modify items:
prices = [100, 200, 300]
for i in range(len(prices)):
prices[i] = prices[i] * 2
print(prices)Output:
[200, 400, 600]Getting both with enumerate()
The built-in enumerate() gives you the index and the item together, which is cleaner than range(len()) when you only need to read:
fruits = ["apple", "banana", "mango"]
for index, fruit in enumerate(fruits):
print(index, fruit)Output:
0 apple
1 banana
2 mangoCommon List Operations
Membership: in and not in
fruits = ["apple", "banana", "mango"]
print("mango" in fruits)
print("grapes" in fruits)
print("grapes" not in fruits)Output:
True
False
TrueConcatenation (+) and Repetition (*)
a = [1, 2, 3]
b = [4, 5]
print(a + b)
print(b * 3)
print(["-"] * 4)Output:
[1, 2, 3, 4, 5]
[4, 5, 4, 5, 4, 5]
['-', '-', '-', '-']Both create a new list; the original lists are not changed.
Useful Built-in Functions
marks = [85, 92, 78, 64, 99]
print(len(marks))
print(sum(marks))
print(min(marks))
print(max(marks))
print(sorted(marks))
print(sum(marks) / len(marks))Output:
5
418
64
99
[64, 78, 85, 92, 99]
83.6sorted() returns a new sorted list and leaves marks unchanged.
Comparing Lists
== checks whether two lists have the same items in the same order:
print([1, 2, 3] == [1, 2, 3])
print([1, 2, 3] == [3, 2, 1])Output:
True
FalseNested Lists (2D Lists)
A list can contain other lists. This is how we represent tables, grids and matrices:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1]) # second row
print(matrix[1][2]) # row 1, column 2
print(matrix[-1][0]) # last row, first columnOutput:
[4, 5, 6]
6
7matrix[1][2] is read in two steps: matrix[1] gives the row [4, 5, 6], and then [2] picks 6 from it. To process every value, use nested loops, as shown in the Nested Loops chapter.
Copying a List: A Very Common Trap
Look at this code carefully:
a = [1, 2, 3]
b = a
b[0] = 100
print(a)
print(b)Output:
[100, 2, 3]
[100, 2, 3]Changing b also changed a! That's because b = a does not copy the list. It just creates a second name for the same list:
a ---\
+---> [100, 2, 3]
b ---/To get an independent copy, use slicing or list():
a = [1, 2, 3]
b = a[:] # or: b = list(a)
b[0] = 100
print(a)
print(b)
print(a is b)Output:
[1, 2, 3]
[100, 2, 3]
FalseThe is operator checks whether two names point to the same object, while == checks whether the contents are equal.
Note:
a[:]andlist(a)make a shallow copy. For nested lists, the inner lists are still shared. To fully copy nested lists, usecopy.deepcopy()from thecopymodule.
The 2D List Creation Trap
A related mistake happens when creating a grid with *:
grid = [[0] * 3] * 3
grid[0][0] = 5
print(grid)Output:
[[5, 0, 0], [5, 0, 0], [5, 0, 0]]* 3 repeated the same inner list three times, so changing one row changed all of them. Create each row separately instead (append() adds an item to the end of a list, and _ is a common name for a loop variable you don't use):
grid = []
for _ in range(3):
grid.append([0] * 3)
grid[0][0] = 5
print(grid)Output:
[[5, 0, 0], [0, 0, 0], [0, 0, 0]](You'll learn a shorter way to write this in the Comprehensions chapter.)
Time Complexity of Common Operations
Internally, a Python list is a dynamic array: references to the items are stored in one continuous block of memory, and the list grows automatically when needed. This explains the cost of each operation:
Operation | Example | Time |
|---|---|---|
Access by index |
| O(1) |
Update by index |
| O(1) |
Length |
| O(1) |
Search |
| O(n) |
Slice |
| O(j - i) |
Delete by index |
| O(n) (items after |
Concatenate |
| O(len(a) + len(b)) |
Sum / min / max |
| O(n) |
Summary
A list is an ordered, mutable collection written with square brackets:
[1, 2, 3].Indexing and slicing work just like strings; a slice returns a new list.
Unlike strings, you can change list items with
a[i] = valueand remove them withdel.Loop over items directly, with
range(len()), or withenumerate().in,+,*,len(),sum(),min(),max()andsorted()all work on lists.b = adoes not copy a list. Usea[:]orlist(a).Never build a 2D list with
[[0] * n] * m.
Lists are Python's everyday container: ordered, flexible, and changeable. Just remember that assignment shares a list, it doesn't copy it.