Lists in Python
A list is an ordered, mutable collection of items enclosed in square brackets [ ]. Items can be of any data type, and a single list can hold mixed types. Lists are one of the most frequently used data structures in Python.
---
Creating a List
```
empty = []
numbers = [1, 2, 3, 4, 5]
mixed = [10, "hello", 3.14, True]
nested = [[1, 2], [3, 4]] # list of lists
```
---
Indexing and Slicing
Lists use zero-based indexing, just like strings. Negative indices count from the end.
Indexing and slicing
```
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[1]) # banana
print(fruits[-1]) # date
print(fruits[1:3]) # ['banana', 'cherry']
```
---
Modifying a List
Unlike strings, lists are mutable — elements can be changed, added, or removed.
Updating elements
```
nums = [10, 20, 30]
nums[1] = 99
print(nums) # [10, 99, 30]
```
---
List Methods
Adding elements
```
lst = [1, 2, 3]
lst.append(4) # adds 4 at end → [1, 2, 3, 4]
lst.insert(1, 99) # inserts 99 at index 1 → [1, 99, 2, 3, 4]
lst.extend([5, 6]) # appends all elements of another list
```
Removing elements
```
lst = [10, 20, 30, 20]
lst.remove(20) # removes first occurrence of 20
lst.pop() # removes and returns last element
lst.pop(0) # removes element at index 0
lst.clear() # removes all elements
```
---
Searching and Sorting
Useful methods
```
marks = [72, 55, 88, 63, 88]
print(marks.index(88)) # 2 (index of first 88)
print(marks.count(88)) # 2 (occurrences of 88)
marks.sort() # sorts in ascending order in-place
print(marks) # [55, 63, 72, 88, 88]
marks.sort(reverse=True) # descending
marks.reverse() # reverses in-place
```
---
List Comprehension
A list comprehension provides a concise way to create a list from an iterable, optionally filtering elements.
Syntax: [expression for item in iterable if condition]
Squares of even numbers from 1 to 10
```
evenssq = [x · · 2 for x in range(1, 11) if x % 2 == 0]
print(evenssq) # [4, 16, 36, 64, 100]
```
---
Built-in Functions with Lists
Aggregate functions
```
data = [3, 1, 4, 1, 5, 9, 2]
print(len(data)) # 7
print(min(data)) # 1
print(max(data)) # 9
print(sum(data)) # 25
print(sorted(data)) # [1, 1, 2, 3, 4, 5, 9] — new sorted list
```
del keyword removes elements by index: del lst[2] deletes the third element.
---
Common mistakes
- Confusing append() and extend() — append adds a single item; extend adds all items of an iterable.
- remove() with a non-existent value — raises ValueError; use a check with in first.
- Aliasing vs copying — b = a makes b point to the same list; use b = a.copy() or b = a[:] for an independent copy.
- Modifying a list while iterating — iterate over a copy to avoid skipping elements.
---
Summary
Lists are ordered, mutable sequences. They support indexing, slicing, all common sequence operations, and a rich set of methods (append, insert, remove, pop, sort, reverse). List comprehensions offer a powerful one-line way to build new lists.