Python Lists and Dynamic Arrays
Master Python lists—dynamic, ordered, and mutable collections. Learn indexing, slicing, common methods, memory allocation, and list copying.
Up until this point, every variable you created held only a single value at a time: age = 25, name = "Alice", or is_logged_in = True.
In real-world software, data arrives in groups:
- A digital shopping cart holding dozens of products.
- A playlist holding hundreds of songs in a specific order.
- A weather app tracking hourly temperature readings over a week.
Creating separate variables like song1, song2, song3… up to song500 would be tedious and impossible to maintain.
To solve this, programming languages provide data structures. In Python, the most versatile, foundational, and frequently used data structure is the List.
1. What Is a List?
A list is an ordered, mutable (changeable) collection of items enclosed in square brackets ([...]).
# A list of string items
grocery_list = ["Apples", "Almond Milk", "Whole Grain Bread", "Eggs"]
# A list of integers
prime_numbers = [2, 3, 5, 7, 11]
# An empty list ready to store future items
inbox = []
# Or using the constructor:
cart = list()
print("Grocery list:", grocery_list)
print("Total grocery items:", len(grocery_list))
Output:
Grocery list: ['Apples', 'Almond Milk', 'Whole Grain Bread', 'Eggs']
Total grocery items: 4
Python Lists Are Heterogeneous
Unlike arrays in languages like C, Java, or C++ (which can only store items of a single predefined type), Python lists can hold any combination of data types:
user_profile = ["alex_dev", 28, 98.6, True, ["Python", "Rust"]]
In this single list, we stored a string, an integer, a float, a boolean, and even another list!
2. Accessing and Modifying Elements
Zero-Based Indexing and Negative Offsets
Just like with strings, items in a list have a fixed position called an index, starting at 0:
Index: 0 1 2 3
List: ["Apples", "Milk", "Bread", "Eggs"]
Negative: -4 -3 -2 -1
groceries = ["Apples", "Milk", "Bread", "Eggs"]
print("First item:", groceries[0]) # Apples
print("Last item:", groceries[-1]) # Eggs
print("Second item:", groceries[1]) # Milk
Lists Are Mutable!
Here is the superpower of lists: unlike strings (which are immutable and cannot be altered), lists are fully mutable. You can overwrite elements in place:
groceries = ["Apples", "Milk", "Bread", "Eggs"]
# Change "Milk" to "Oat Milk"
groceries[1] = "Oat Milk"
print("Updated list:", groceries)
Output:
Updated list: ['Apples', 'Oat Milk', 'Bread', 'Eggs']
Slicing Lists
You can extract a sub-list using the slice syntax [start:stop:step] (identical to strings):
letters = ["a", "b", "c", "d", "e", "f"]
print("First three:", letters[:3]) # ['a', 'b', 'c']
print("Middle two:", letters[2:4]) # ['c', 'd']
print("Every other item:", letters[::2]) # ['a', 'c', 'e']
print("Reversed:", letters[::-1]) # ['f', 'e', 'd', 'c', 'b', 'a']
3. Essential List Methods: Adding Items
Python lists grow and shrink dynamically as your program runs.
1. .append(item): Add to the End
Places a new item at the very end of the list in amortized $O(1)$ constant time:
tasks = ["wash dishes", "clean room"]
tasks.append("take out trash")
print(tasks) # ['wash dishes', 'clean room', 'take out trash']
2. .insert(index, item): Add at a Specific Position
Places a new item at an exact index, shifting all subsequent items one spot to the right ($O(n)$ time):
tasks = ["wash dishes", "clean room"]
tasks.insert(1, "walk the dog")
print(tasks) # ['wash dishes', 'walk the dog', 'clean room']
3. .extend(iterable) vs .append(iterable)
This is one of the most common beginner mix-ups:
# Example with append:
numbers1 = [1, 2, 3]
numbers1.append([4, 5])
print("Using append:", numbers1)
# Output: [1, 2, 3, [4, 5]] -> Nested list!
# Example with extend:
numbers2 = [1, 2, 3]
numbers2.extend([4, 5])
print("Using extend:", numbers2)
# Output: [1, 2, 3, 4, 5] -> Flattened items unpacked!
[!NOTE]
.append(x)treatsxas a single unit (even ifxis another list)..extend(x)loops throughxand appends every individual element.
4. Essential List Methods: Removing Items
1. .pop([index]): Remove and Return
Removes the element at index and hands it back to you. If no index is provided, it removes and returns the last item:
stack = ["page1", "page2", "page3"]
current_page = stack.pop()
print("Popped page:", current_page) # 'page3'
print("Remaining stack:", stack) # ['page1', 'page2']
first_page = stack.pop(0)
print("Popped first:", first_page) # 'page1'
print("Remaining stack:", stack) # ['page2']
2. .remove(value): Find and Delete by Value
Searches the list from left to right and deletes the first occurrence of value:
colors = ["red", "blue", "green", "blue"]
colors.remove("blue")
print(colors) # ['red', 'green', 'blue'] (only the first 'blue' was deleted!)
[!CAUTION] If the value does not exist,
.remove()raises aValueError: list.remove(x): x not in list. Always verify withif value in colors:before calling.remove().
3. del Statement and .clear()
items = ["a", "b", "c", "d", "e"]
# Delete an item or a slice:
del items[1] # Deletes 'b'
del items[1:3] # Deletes 'c' and 'd'
print(items) # ['a', 'e']
# Empty the entire list:
items.clear()
print(items) # []
5. Sorting and Ordering: .sort() vs sorted()
Understanding the difference between the .sort() method and the sorted() function will save you hours of debugging:
.sort(): In-Place Modification
Modifies the existing list directly in memory. Returns None!
scores = [45, 99, 12, 78, 63]
scores.sort() # Ascending order
print("Sorted scores:", scores) # [12, 45, 63, 78, 99]
scores.sort(reverse=True) # Descending order
print("Descending:", scores) # [99, 78, 63, 45, 12]
[!WARNING] A common beginner mistake is writing
result = scores.sort(). Because.sort()modifies the list in place, it returnsNone, soresultwill beNone!
sorted(): Non-Destructive Copy
Leaves the original list completely untouched and returns a brand-new sorted list:
original = [5, 2, 8, 1]
fresh_copy = sorted(original)
print("Original untouched:", original) # [5, 2, 8, 1]
print("New sorted list:", fresh_copy) # [1, 2, 5, 8]
6. The Memory Trap: Assignment vs Copying
Recall the sticky-note mental model from variables. Variables in Python are labels pointing to objects in memory.
If you assign one list variable to another, you are NOT creating a second list! You are simply pasting a second sticky note on the exact same box in RAM:
list_a = [1, 2, 3]
list_b = list_a # Both variables point to the identical list object!
list_b.append(99)
print("list_b:", list_b) # [1, 2, 3, 99]
print("list_a:", list_a) # [1, 2, 3, 99] -> Surprising side effect!
How to Create a Real (Shallow) Copy
To duplicate a list so modifications to one do not alter the other:
list_a = [1, 2, 3]
# Method 1: The .copy() method
copy_1 = list_a.copy()
# Method 2: Full slice
copy_2 = list_a[:]
# Method 3: list() constructor
copy_3 = list(list_a)
copy_1.append(999)
print("list_a remains intact:", list_a) # [1, 2, 3]
print("copy_1:", copy_1) # [1, 2, 3, 999]
For nested lists (lists inside lists), use copy.deepcopy() from the standard library:
import copy
nested_matrix = [[1, 2], [3, 4]]
deep_clone = copy.deepcopy(nested_matrix)
7. Performance & Big-O Complexity
Under the hood, CPython implements lists as dynamic arrays of pointers. Understanding their operation costs helps you write fast code:
| Operation | Syntax | Time Complexity | Note |
|---|---|---|---|
| Index lookup | list[i] | $O(1)$ | Direct pointer arithmetic |
| Append | list.append(x) | $O(1)$ amortized | Fast; CPython over-allocates buffer space |
| Pop from end | list.pop() | $O(1)$ | No memory elements need to move |
| Insert / Pop at start | list.insert(0, x) | $O(n)$ | Slow; all $n$ items must slide right/left |
| Search / Contains | x in list | $O(n)$ | Linear scan through items |
| Sort | list.sort() | $O(n \log n)$ | Uses Timsort (adaptive merge sort) |
Summary & What’s Next
- Lists are ordered, mutable sequences defined with
[...]. - Use
.append()to add items to the end,.insert()to place items anywhere, and.extend()to merge sequences. - Remove items with
.pop()(by index) or.remove()(by value). - Remember that
b = acreates an alias, not a copy; use.copy()or[:]for independent lists.
If you need a sequence that is guaranteed never to change and can safely act as a dictionary key, move on to tuples.