Lesson 1 of 4
Store many values in order with lists: access and slice them, add and remove items, sort them, and summarise numeric data.
About 30 minutes
append(), insert() and remove()len(), sum(), min() and max()A variable holds one value. Scientific work usually involves many related values: a series of temperature readings, the elements in an alloy, the masses of a set of samples. Creating reading1, reading2, reading3 and so on quickly becomes unmanageable. Python's data structures (also called collections) store many values under a single name. This module covers the four built-in ones: lists, tuples, dictionaries and sets.
A list holds values in a fixed order. Write the values inside square brackets, separated by commas. A list can hold any type of value, including a mix of types, and len() tells you how many items it contains.
temperatures = [293, 310, 350, 400] # Kelements = ["Fe", "Cr", "Ni"]sample = ["Cu-01", 8.96, True] # mixed types are allowedempty = []print(temperatures)print(len(elements))print(len(empty))Lists use the same indexing and slicing as strings. The first item is at index 0, negative indexes count from the end, and [start:stop] gives a new list containing the items from start up to, but not including, stop.
temperatures = [293, 310, 350, 400]print(temperatures[0]) # firstprint(temperatures[-1]) # lastprint(temperatures[1:3]) # items 1 and 2IndexError
temperatures[4] in a four-item list, raises an IndexError: list index out of range. Remember that the last valid index is one less than the length.Unlike strings, lists are mutable: you can change them after creating them. Assign to an index to replace an item, or use list methods to add and remove items. These methods change the list in place and don't return a new list.
| Method | What it does |
|---|---|
append(x) | Add x to the end |
insert(i, x) | Insert x at index i, moving later items along |
extend(other) | Add every item from another list to the end |
remove(x) | Remove the first item equal to x |
pop() | Remove and return the last item (or pop(i) for index i) |
index(x) | Return the index of the first item equal to x |
count(x) | Count how many items equal x |
samples = ["Cu", "Al", "Fe"]samples.append("Ti") # add to the endsamples.insert(1, "Ni") # add at index 1samples[0] = "Cu-annealed" # replace an itemsamples.remove("Al") # remove by valuelast = samples.pop() # remove and keep the last itemprint(samples)print("Removed:", last)The in operator checks whether a value is in a list and returns True or False. not in checks the opposite.
alloy = ["Fe", "Cr", "Ni"]print("Cr" in alloy)print("Mo" in alloy)print("Mo" not in alloy)There are two ways to sort. The method list.sort() sorts the list itself (in place). The built-in function sorted(list) leaves the original alone and returns a new sorted list. Both sort numbers from smallest to largest and text alphabetically. Add reverse=True to sort the other way.
melting_points = [1538, 660, 1085, 3422]print(sorted(melting_points))print(melting_points) # unchangedmelting_points.sort(reverse=True)print(melting_points) # now changedThe built-in functions len(), sum(), min() and max() work on any list of numbers. Together they give a quick summary of a dataset, including the mean (the sum divided by the count).
Five Vickers hardness measurements were taken across a steel sample.
hardness = [152, 160, 158, 149, 155] # HVmean_hardness = sum(hardness) / len(hardness)print(f"Measurements: {len(hardness)}")print(f"Range: {min(hardness)} to {max(hardness)} HV")print(f"Mean: {mean_hardness:.1f} HV")A list can contain other lists. This is a simple way to store a table: each inner list is a row. Use two indexes to reach a single value: the first picks the row, the second picks the item in that row.
# Each row: [temperature in K, resistance in ohms]measurements = [ [293, 1.72], [323, 1.92], [373, 2.26],]print(measurements[1]) # the second rowprint(measurements[1][1]) # resistance in the second rowCopying a list
b = a does not copy a list. Both names then refer to the same list, so changing b also changes a. Use b = a.copy() when you need an independent copy.original = [1.0, 2.0, 3.0]same_list = originalreal_copy = original.copy()same_list.append(4.0)print(original) # changed too!print(real_copy) # unaffectedChoose an answer and press Check answer. You can retry as often as you like.