Tuples

A tuple is a sequence that cannot change

t = (10, 20, 30)100-3201-2302-1t[0] is 10t[-1] is 30t[1:] is (20, 30)t[0] = 99TypeError: a tuple does notsupport item assignmentA tuple is a sequence that cannot change.It is made with round brackets and read exactly like a list: indexes, negative indexes,slices, len(), in and for all work. What it has not got is any way to add, remove or replacean item. There is no append() and no del t[0]. That property is called immutability.

Round brackets. Read like a list. Immutable.

Tuples · Going deeper

Writing a tuple

CodeTypeNote()tupleAn empty tuple; its length is 0(5,)tupleOne item: the comma is what makes it a tuple(5)intJust the number 5 in brackets1, 2tupleThe brackets are optional; the commas are not(1, 2) + (3,)tupleA new tuple: (1, 2, 3)(1, 2) * 2tupleA new tuple: (1, 2, 1, 2)x, y = (1, 2)Unpacking: x is 1 and y is 2A one-item tuple needs a trailing comma.(5) is an int and (5,) is a tuple. The exam asks for the type, or the len(), of each.

(5,) is a tuple. (5) is an int.

Tuples and lists

The tuple is fixed. A list inside it is not.

t = (1, [2, 3])t[1].append(4)print(t)t1•[0][1]the list t[1] refers to234prints (1, [2, 3, 4])The tuple is fixed. A list inside it is not.A tuple cannot be made to hold a different item, but it does not freeze the items it holds.t[1] is still the same list, so t[1].append(4) is allowed. t[1] = [9] is not: that wouldreplace an item of the tuple. Read nested indexes left to right: t[1][0] is 2.

Cannot replace an item. Can change a mutable item.

Tuples and lists · Going deeper

List or tuple

ListTupleWritten with[1, 2, 3](1, 2, 3)Ordered, indexed, slicedYesYesCan be changedYes: mutableNo: immutableappend(), insert(), del, sort()YesNolen(), in, for, +, *YesYesUse forA collection that grows or changesA fixed group, such as a point (x, y)t = t + (4,) is allowed, and does not change any tuple.It builds a new tuple and moves the name t to it. Reassigning a name is always possible.Immutability is about the object, not about the name.

Mutable or immutable.

Check yourself

a = (5)b = (5,)print(type(a) == type(b), len(b))

What does this print?

Sets

A set keeps one of each value, in no order

s = {3, 1, 3, 2, 1}123repeats are dropped: len(s) is 3s.add(5)1235a new value goes ins.add(1)1235already there: nothing changess.remove(3)1253 is taken outA set keeps one of each value, in no particular order.Curly brackets with single values make a set. It has no first item and no index: s[0] isa TypeError. What a set is good at is the question "is this value in it?", asked with in.

Unique values. No index. add() and remove().

Sets · Going deeper

Set facts

CodeGivesNoteset()an empty setThe only way to write one{}an empty dictNot a set2 in {1, 2, 3}Truein and not in work as for lists{1, 2, 3}[0]TypeErrorNo positions, so no indexing and no slicings.remove(9)KeyErrorRemoving a value that is not theres.discard(9)nothingThe same, without the errorlen(set([1, 2, 2, 3, 3, 3]))3set() of a list drops the repeatslen(set('hello'))4h, e, l, oDo not rely on the order a set prints in.Ask a set for its length or whether a value is in it. A position has no meaning.

set() is empty. {} is a dict.

Dictionaries

A dictionary finds a value by its key, not its position

d = {'ann': 31, 'bob': 25}'ann': 31'bob': 25d['cy'] = 40'ann': 31'bob': 25'cy': 40a new key: the pair is addedd['bob'] = 26'ann': 31'bob': 26'cy': 40an existing key: the value is replaceddel d['ann']'bob': 26'cy': 40the pair is removedA dictionary finds a value by its key, not by its position.Each item is a key and a value, written key: value. d['ann'] looks up the value for thatkey. The same square brackets on the left of = add a pair or replace a value.

key: value. d[key] reads, adds and replaces.

Dictionaries · Going deeper

Dictionary facts

d = {'bob': 26, 'cy': 40}CodeGivesNoted['cy']40Look up by keyd['zed']KeyErrorA key that is not there'bob' in dTruein tests the keys26 in dFalsenot the valueslen(d)2The number of pairs{'a': 1, 'a': 2}{'a': 2}A key appears once; the last value winsd[[1, 2]] = 'x'TypeErrorA key must be immutable: a list cannot be oneKeys are unique. Values can be anything, and can repeat.Numbers, strings and tuples can be keys. Check with in before reading a key that may be missing.

in tests keys. Missing key: KeyError.

Check yourself

s = {1, 2, 2, 3}s.add(2)s.add(4)print(len(s))

What does this print?

Dictionary methods

Looping over a dictionary gives its keys

d = {'a': 1, 'b': 2}d.keys()'a', 'b'the keysd.values()1, 2the valuesd.items()('a', 1), ('b', 2)each pair, as a tuplefor k, v in d.items(): print(k, v)prints a 1, then b 2for k in d: gives the keys onlyLooping over a dictionary gives its keys. items() gives both.A dictionary keeps its pairs in the order they were added, so the loop follows that order.

keys(), values(), items().

Dictionary methods · Going deeper

Five collections compared

listtuplesetdictstrWritten[1, 2](1, 2){1, 2}{'a': 1}'ab'Orderedyesyesnoby insertionyesIndexed bypositionpositionnothingkeypositionMutableyesnoyesyesnoRepeatsallowedalloweddroppedkeys: noallowedEmpty[]()set(){}''Five collections, and six questions that tell them apart.Which brackets, is there an order, how do you reach an item, can it change, are repeats kept,and how is the empty one written. Most collection questions are one of these.

list, tuple, set, dict, str.

Check yourself

d = {'x': 1, 'y': 2}d['x'] = d['y'] + 1d['z'] = d['x'] * 2print(d['z'], len(d))

What does this print?

Lesson complete

You finished “Tuples, sets and dictionaries”

Answer the questions along the way to see your score here.

Open in a new tab