
This section explores Python’s built-in data structures in greater detail, covering both familiar concepts and new techniques.
Lists: Advanced Usage
Python’s list data type offers several useful methods for manipulation:
Essential List Methods
append(x)
Adds an item to the end of the list. Equivalent toa[len(a):] = [x]
.extend(iterable)
Extends the list by appending all items from an iterable. Similar toa[len(a):] = iterable
.insert(i, x)
Inserts an item at a specified position. The index argument determines where the insertion occurs, soinsert(0, x)
adds to the beginning, whileinsert(len(a), x)
behaves likeappend(x)
.remove(x)
Removes the first occurrence of a value. RaisesValueError
if the value doesn’t exist.pop([i])
Removes and returns an item at the given index (last item if no index is provided). RaisesIndexError
for invalid indices.clear()
Removes all items from the list. Equivalent todel a[:]
.index(x[, start[, end]])
Returns the first index of a value, with optional search bounds. RaisesValueError
if not found.count(x)
Counts occurrences of a value in the list.sort(*, key=None, reverse=False)
Sorts items in place. Parameters allow customization (seesorted()
for details).reverse()
Reverses list elements in place.copy()
Returns a shallow copy of the list. Equivalent toa[:]
.
Practical Example
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] print(fruits.count('apple')) # Output: 2 fruits.reverse() print(fruits) # Output: ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange'] fruits.sort() print(fruits) # Output: ['apple', 'apple', 'banana', 'banana', 'kiwi', 'orange', 'pear']
Note that methods like insert()
, remove()
, and sort()
modify the list and return None
by design—a Python convention for mutable data structures.
Special Considerations
- Not all data types are comparable. For example,
[None, 'hello', 10]
cannot be sorted due to incompatible types. - Some types lack defined ordering (e.g., complex numbers with
3+4j < 5+7j
is invalid).
Using Lists as Stacks
Lists efficiently emulate stacks (last-in, first-out):
- Push: Use
append()
- Pop: Use
pop()
Example:
stack = [3, 4, 5] stack.append(6) # Stack becomes [3, 4, 5, 6] stack.pop() # Returns 6
Using Lists as Queues (Inefficient)
For queues (first-in, first-out), lists are suboptimal because popping from the front is slow. Instead, use collections.deque
:
from collections import deque queue = deque(["Eric", "John", "Michael"]) queue.append("Terry") queue.popleft() # Returns "Eric"
List Comprehensions
A concise way to create lists by applying operations to iterables:
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, ..., 81]
Comprehensions can include multiple for
and if
clauses:
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] # Output: [(1, 3), (1, 4), (2, 3), ...]
Nested List Comprehensions
Useful for complex structures like matrix transposition:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] [[row[i] for row in matrix] for i in range(3)] # Transposes rows/columns
For real-world use, prefer zip(*matrix)
.
Tuples
Immutable sequences, often for heterogeneous data:
t = 12345, 54321, 'hello!' x, y, z = t # Unpacking
- Empty tuples:
()
- Singleton tuples require a trailing comma:
('hello',)
Sets
Unordered collections of unique elements:
basket = {'apple', 'orange', 'apple'} # Duplicates removed print('orange' in basket) # Membership test: True
Set operations (|
, &
, -
, ^
) are supported.
Dictionaries
Key-value mappings with unique, immutable keys:
tel = {'jack': 4098, 'sape': 4139} tel['guido'] = 4127 # Add/update print(list(tel)) # ['jack', 'sape', 'guido']
Dictionary comprehensions:
{x: x**2 for x in (2, 4, 6)} # {2: 4, 4: 16, 6: 36}
Looping Techniques
- Dictionaries: Use
items()
:pythonCopyfor k, v in knights.items(): print(k, v) - Sequences: Use
enumerate()
for indices:pythonCopyfor i, v in enumerate([‘tic’, ‘tac’]): print(i, v) - Multiple sequences: Combine with
zip()
:pythonCopyfor q, a in zip(questions, answers): print(f”What’s your {q}? It’s {a}.”) - Reversed/Sorted:pythonCopyfor i in reversed(range(1, 10, 2)): print(i) # 9, 7, …, 1 for f in sorted(set(basket)): print(f) # Unique items sorted
Comparisons and Conditions
- Chained comparisons:
a < b == c
- Short-circuit operators:
or
/and
return the last evaluated argument. - Sequence comparisons are lexicographical.
Example:
(1, 2, 3) < (1, 2, 4) # True 'ABC' < 'Python' # True