Python Lists: The Swiss Army Knife
A
list is a mutable, ordered sequence of items. It's one of Python's most frequently used data structures. You can put items of different types in a single list, though we usually keep them consistent.python
Creating Lists
python
Accessing and Slicing
Python's indexing is zero-based, and it also supports negative indexing for accessing items from the end.
python
Modifying Lists: Most Common Methods
| Method | Action | Example |
|---|---|---|
| .append(x) | Add x to the end | nums.append(100) |
| .extend(list) | Concatenate list | nums.extend([2, 3]) |
| .insert(i, x) | Insert x at index i | nums.insert(0, 5) |
| .remove(x) | Remove first item x | nums.remove(40) |
| .pop(i) | Remove and return item i | val = nums.pop() |
| .sort() | Sort in place | nums.sort(reverse=True) |
| .index(x) | Get index of x | idx = nums.index(30) |
python
List Comprehensions: The Pythonic Way!
This allows you to create lists using a concise, readable syntax. It's often faster than a standard
for loop.python
Sorting and Ordering
- list.sort(): Modifies the list directly.
- sorted(list): Returns a new sorted list (works on any iterable).
python
List Unpacking (Python 3.5+)
python
Summary
| Feature | Method / Syntax |
|---|---|
| Add | .append(), .extend(), .insert() |
| Remove | .pop(), .remove(), del list[i] |
| Search | .index(), .count(), x in list |
| Copy | list[:] or .copy() |
| Construct | [x for x in seq] |