Lists are one of Python's most-used data structures: ordered, indexable from both ends using positive and negative indices, allow duplicate values, and support in-place mutation through methods like append(), extend(), insert(), remove(), and slicing assignment. Internally, CPython implements a list as a dynamic array of object pointers, so indexing is O(1) but inserting or removing from the front is O(n) since every following element has to shift.
1Understanding Lists
Lists are one of Python's most-used data structures: ordered, indexable from both ends using positive and negative indices, allow duplicate values, and support in-place mutation through methods like append(), extend(), insert(), remove(), and slicing assignment. Internally, CPython implements a list as a dynamic array of object pointers, so indexing is O(1) but inserting or removing from the front is O(n) since every following element has to shift.
Appending to the end of a list is amortized O(1), but inserting at the front is O(n) — use collections.deque instead if you need fast operations at both ends.
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
print(fruits[-1])2Practical Example
Here is a real-world application of Lists showing how it is used in production Python code.
matrix = [[1, 2], [3, 4]]
alias = matrix
copy = matrix.copy()
alias[0][0] = 99
print(matrix)
print(copy)3Best Practices
Follow these guidelines when working with Lists:
1. Use a list comprehension instead of a for loop with .append() when building a new list from a transformation
2. Use collections.deque instead of list when you need fast insertion/removal from both ends
3. Be careful with new_list = old_list — it creates an alias, not a copy; use old_list.copy() or a slice to actually duplicate it
Tip: Appending to the end of a list is amortized O(1), but inserting at the front is O(n) — use collections.deque instead if you need fast operations at both ends.
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
print(fruits[-1])