Source
Adapted from my own handwritten and hand-typed notes from Year 1 to Year 3 of my EEE degree
A list is an ordered collection of items. Items are accessed, reassigned or deleted by index, and mixed data types are allowed.
Access, Reassign, Delete
rainfall = [0, 3.2, 15.6, 0.2, 0, 0, 43.8, 0]
rainfall[4] = 0.2 # reassign item at index 4
del rainfall[-1] # delete last item
# rainfall -> [0, 3.2, 15.6, 0.2, 0.2, 0, 43.8]Operations Shared with Strings
Many str operations also work on lists:
rainfall += [0, 0, 0] # concatenate
len(rainfall) # 10
rainfall.count(0) # 5
rainfall.index(15.6) # 2Slicing
Same [start:stop:step] rule as strings, and slices can also be reassigned or deleted:
rainfall = [0, 3.2, 15.6, 0.2, 0.2, 0, 43.8]
rainfall[2:5] # [15.6, 0.2, 0.2] third to fifth items
rainfall[::-1] # all items, reversed
rainfall[:-2] # all except last two
rainfall[-2:] = [0.4, 6.2] # reassign last two items
del rainfall[-3:] # delete last three itemsAdding and Removing Items
| Method | What it does |
|---|---|
append(x) | add x at the end |
insert(i, x) | add x at index i, later indices shift right |
remove(x) | delete the first occurrence of value x |
pop(i) | remove the item at index i and return it |
rainfall = [0, 3.2, 0.2, 0.2, 0]
rainfall.append(43.8) # [0, 3.2, 0.2, 0.2, 0, 43.8]
rainfall.insert(2, 15.6) # [0, 3.2, 15.6, 0.2, 0.2, 0, 43.8]
rainfall.pop(4) # returns 0.2Sorting
sort() sorts in ascending order, sort(reverse=True) in descending order. It works in place, so the original order is lost.
rainfall.sort() # [0, 0, 0.2, 3.2, 15.6, 43.8]
rainfall.sort(reverse=True) # [43.8, 15.6, 3.2, 0.2, 0, 0]Nested Lists
A list can hold other lists (or tuples, dicts, sets) as items:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8]]
type(matrix[1]) # <class 'list'>
type(matrix[1][2]) # <class 'int'>, value 6 (row 1, item 2)
len(matrix) # 3
len(matrix[2]) # 2For large numeric data, numpy arrays are faster than nested lists. Other built-in collections are compared in Tuples Dictionaries and Sets.