What Is a List in Python?
A list is an ordered, mutable collection of elements. It allows you to store multiple values in a single variable.
Lists are defined using square brackets.
numbers = [1, 2, 3, 4] names = ["Alice", "Bob", "Charlie"] mixed = [1, "Python", 3.14, True]
Key Characteristics of Lists
- Ordered – elements maintain their position
- Mutable – elements can be changed
- Dynamic – size can grow or shrink
- Allows duplicate values
Accessing List Elements
List elements are accessed using indexing. Indexing starts from 0.
languages = ["Python", "Java", "C++"] print(languages[0]) print(languages[-1])
List Slicing
Slicing allows you to extract a portion of a list.
nums = [0, 1, 2, 3, 4, 5] print(nums[1:4]) print(nums[:3]) print(nums[::2])
Modifying Lists
Lists can be modified after creation.
Changing Elements
nums[0] = 100
Adding Elements
nums.append(6) nums.insert(1, 50)
Removing Elements
nums.remove(50) nums.pop() del nums[0]
Common List Methods
Python provides built-in methods to operate on lists.
items = [3, 1, 4, 1, 5] items.sort() items.reverse() count = items.count(1) index = items.index(4)
Iterating Over Lists
Lists are commonly used with loops.
for item in items:
print(item)
Using enumerate()
for index, value in enumerate(items):
print(index, value)
List Concatenation and Repetition
a = [1, 2] b = [3, 4] print(a + b) print(a * 3)
Nested Lists
Lists can contain other lists.
matrix = [
[1, 2, 3],
[4, 5, 6]
]
print(matrix[1][2])
List Comprehensions
List comprehensions provide a concise way to create lists using expressions.
squares = [x * x for x in range(5)]
Shallow vs Deep Copy
Understanding copying is important with mutable objects.
a = [1, 2, 3] b = a.copy()
Nested lists require deep copying to avoid shared references.
Common List Operations Summary
| Operation | Description |
|---|---|
| append() | Add item at the end |
| insert() | Add item at specific index |
| remove() | Remove first matching item |
| pop() | Remove and return item |
| sort() | Sort the list |
Performance Considerations
Lists are implemented as dynamic arrays.
- Fast access by index
- Appending is efficient
- Insertion in the middle is slower
Common Beginner Mistakes
- Modifying a list while iterating
- Confusing remove() and pop()
- Unexpected behavior with nested lists
Real-World Example
A to-do application stores tasks in a list, adds new tasks dynamically, removes completed ones, and displays them in order. Lists provide the flexibility needed for such dynamic collections.
Summary
Lists are mutable, ordered collections that form the backbone of many Python programs. They support powerful operations like slicing, iteration, comprehensions, and sorting. Understanding list behavior, methods, and performance trade-offs is essential for writing efficient and maintainable Python code. Mastery of lists unlocks more advanced data structures and real-world problem-solving patterns.