Lesson 2 of 4
Use tuples for fixed groups of values such as coordinates or records, and unpack them into separate variables.
About 20 minutes
A tuple is an ordered collection, like a list, but it cannot be changed after it is created: you can't add, remove or replace items. Tuples are written with round brackets instead of square ones.
position = (0.25, 0.25, 0.25) # fractional coordinates of an atomlattice = (5.431, 5.431, 5.431) # a, b, c of silicon in Åelement = ("Si", 14, 28.085) # symbol, atomic number, atomic massprint(position)print(element[0])print(len(lattice))Indexing, slicing, len() and in all work exactly as they do for lists. A tuple with only one item needs a trailing comma, (5,), otherwise Python reads the brackets as ordinary maths brackets.
(x, y, z), lattice parameters (a, b, c) or an element's (symbol, number, mass) always have the same number of parts in the same order. A tuple says this group belongs together and shouldn't change.A good rule of thumb: use a list for a varying number of similar things (all the measurements in an experiment), and a tuple for a fixed number of related things (one measurement's temperature and value).
lattice = (5.431, 5.431, 5.431)lattice[0] = 5.5Trying to change a tuple raises TypeError: 'tuple' object does not support item assignment. If you need a changed version, create a new tuple.
Unpacking assigns each item of a tuple to its own variable in a single line. The number of variables on the left must match the number of items. This makes code that works with records much easier to read: a, b, c = lattice is clearer than using lattice[0], lattice[1] and lattice[2].
An orthorhombic unit cell has three different lattice parameters. Unpacking them makes the volume formula easy to read.
lattice = (4.76, 10.20, 5.98) # a, b, c in Åa, b, c = latticevolume = a * b * cprint(f"a = {a} Å, b = {b} Å, c = {c} Å")print(f"Volume: {volume:.1f} ų")Unpacking makes it easy to swap two variables without a temporary variable. Python builds the tuple on the right first, then unpacks it into the names on the left.
low, high = 1085, 660low, high = high, lowprint(low, high)Because tuples can't change, they only have two methods: count(x) and index(x), which work just like the list versions. You can convert between the two types with list() and tuple(), for example to change a value and then turn the result back into a tuple.
lattice = (5.431, 5.431, 5.431)print(lattice.count(5.431))editable = list(lattice)editable[2] = 5.50lattice = tuple(editable)print(lattice)Choose an answer and press Check answer. You can retry as often as you like.