iBbAfCAeCfACABBrEErAX-~~~| 6A6A64VCB~ 6F-~CWC 6866V 6A64VCC 6464V~Z~~ 6887797VCB 864756475VBCC 65656565VC 68494V 764}AW 6A6R64V~CC 699VC 8496964V~~ 49765V 558468}4-~~CC 66F8-~BZX

Tuple.` Consider this starfish. It has 5 arms. It is underwater. These attributes form a unit of information—they could be stored together in a tuple.`Python tuples` are values—they never change. Suppose an element has a shape and a color. This forms a tuple pair. Logically this information is a single unit.`Create.` A tuple is immutable—this is important to consider. It cannot be changed after created. So the creation syntax must be used often. We use "(" and ")" to create tuples. `Zero elements: `To create a tuple with zero elements, use only the two parentheses "()".`One element: `For a tuple with one element, use a trailing comma. This helps Python tell that you don't mean an expression, such as (1 + 2).`Two elements: `For a tuple with 2 or more elements, use a comma between elements. No ending comma is needed.`Immutable.` An immutable object cannot be changed. Once created it always has the same values. A tuple is immutable. Here we attempt to assign the first element in the tuple. `But: `This is invalid. When executed, the Python runtime will report a TypeError.`Error `error-python`Create: `To make a new, changed tuple, we would need to create a new tuple. We could specify that some items have the same values.`Immutability.` This part is kind of boring. But the concept of immutable objects is important. It seems inefficient. Why not just modify existing objects? `Dictionary: `Some objects are more efficient when they are immutable. For example, in a dictionary tuples are used.`We can directly access these two-element tuples. If these tuples could be changed, the original dictionary would become invalid.`Pack, unpack.` Tuples can be packed and unpacked. In packing, we place values into a new tuple. And in unpacking we extract those values back into variables. `This syntax form creates elegant and small programs. In this program we pack two strings into a tuple.`Then: `We initialize two variables to those two packed values. The variables act like any other variable.`No parentheses.` Tuples are typically specified with surrounding parentheses chars. But suppose you are a wild one. You can just use a comma. The tuple is inferred. `Add, multiply.` A tuple is not a number. But it can be added to or multiplied. By adding two tuples, they are concatenated. One is put after the other. `By multiplying a tuple with a number, we add the tuple to itself a certain number of times.`Warning: `This syntax form can become somewhat confusing. I have not used it often on tuples.`Divide, subtract.` We cannot divide or subtract tuples. Out of curiosity I tried this. I received the TypeError with "unsupported operand type." `Operand: `As a reminder, an operand is a value on one side of an expression. It is part of an operation.`Max, min.` The max and min functions can be used on tuples. These functions locate the item that would be sorted last (max) or sorted first (min). `Max, min `max-python`For strings: `The comparison performed is alphabetical—"able" comes before "zero". So "able" would be less than "zero".`For numbers: `The comparison is numeric—10 comes before 20. These comparisons are logical.`In keyword.` This example creates a two-element tuple (a pair). It searches the tuple for the string "cat". It then searches for "bird", but this string does not exist. `With the in-keyword, we can search a tuple. We use in as part of an if-statement. And we can combine in with not—this is "not in".`In `in-python`Slice.` A tuple can be sliced. The slice notation uses a colon. On the left side of the colon, we have the starting index. If no starting index is present, the program uses 0. `Slice `slice-python`On the right side of the colon, we have the ending index. If no ending index is present, the last index possible is used.`Slicing creates a new tuple. A slice that specifies no indexes is a simple way to copy a tuple.`Index.` This gets the index of an element. Here we search for the value "dog," and get the index 1 (the second position). If we use index() on a value that is not found, an error results. `Consider the in operator before calling index() on a value that might not exist. This prevents a possible exception.`Count.` This returns the number of elements with a specific value in a tuple. If you need to get the total length of the tuple, please use len. Count only counts certain values. `Keys, dictionary.` We next use a tuple as a dictionary key. Dictionaries can use tuple keys without worrying about them changing. Here we use the pair of values 1 and 2 to look up a value. `You can use tuples in this way to create a two-dimensional dictionary. Use a tuple to represent X and Y coordinates.`Convert.` A tuple cannot be modified. But a list can be changed in many ways. For this reason we often need to convert a tuple into a list. `List: `The list built-in accepts a tuple as its argument. Here we use sort() on the resulting list.`Finally: `In the program, we convert the list back into a tuple. This is done with the tuple() function.`We see that a list has square brackets. A tuple has round ones. This is an important part of Python's syntax.`Enumerate.` This is a built-in method. Enumerate() returns a tuple of an index and the element value at that index. It is often used on a list. `We use enumerate on a list of strings. We can access the tuple, or directly unpack the tuple in the for-statement.`List of tuples.` Let us examine a practical example. This program divides a string into a list of tuples. Each tuple has adjacent characters from the string. `Range: `We use the range built-in to iterate over the string, with a step of 2. We start at index 1 to avoid the first char.`Append: `We call append() on the list (called "pairs") and as the argument to append, we create a two-element tuple (a pair).`Swap.` To flip or swap variables, we do not need a temporary variable. We can use a tuple unpacking expression. We assign each variable to the other one in a single statement. `Performance.` How do we choose between the syntax forms for tuples? In this benchmark we test two ways of assigning variables to values in a tuple. We unpack tuples. `Version 1: `This version of the program uses a single statement to unpack an existing tuple.`Version 2: `This version assigns to the elements in a tuple using the "[" and "]" syntax.`Result: `Version 1, which unpacks the tuple in a single statement, is somewhat faster.`In Python, the number of statements often influences greatly the results. This may change as more advanced compilers appear.`Research.` A tuple is a sequence, much like a list (and not like a class). In the Python documentation, we find that the enumerate() built-in returns tuples. `Quote: `Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in).`Built-in Types: python.org `https://docs.python.org/3/library/stdtypes.html`Namedtuple.` In normal tuples, fields have no names. With namedtuple, a type from the collections module, we can provide names to a tuple's fields. `Namedtuple `namedtuple-python`With tuples,` we have access to many (but not all) of the methods of a list. Tuples are key to other important types, such as dictionary. And they are used, to some advantage, within lists.`Usage.` Tuples are often combined with other types. Often we store tuples within lists to create a list of pairs. In this way we avoid combining values together in strings.

NYXKqXXq# Zero-Y8 tuple.XqaYyq()qX# One-Y8 tuple.XqbYyq(KoneK,)qX# Two-Y8 tuple.XqcYyq(KoneK, KtwoK)qXXY[(a)XY[(len(a))XXY[(b)XY[(len(b))XXY[(c)XY[(len(c))XXqXX()X0X('one',)X1X('one', 'two')X2qXXtupleYy('cat', 'dog', 'mouse')qXX# This causes an error.Xqtuple[0]Yy'feline'XXqResultsqXXTypeError: 'tuple' object does not support item assignmentqXXq# CY_ packed tuple.XqpairYy(qKdogKq, qKcatKq)qXX# Unpack tuple.Xq(key, Yh)YypairqXX# Y= unpacked variables.XqY[(key)XY[(Yh)XXqXXdogXcatqXXq# A trailing comma indicates a tuple.Xqone_itemYyqKcatK,qXX# A tuple can be specified with no parentheses.Xqtwo_itemsYyqKcatK, KdogKqXXY[(one_item)XY[(two_items)XXqXX('cat',)X('cat', 'dog')qXXchecksYy(10, 20, 30)qXX# Add two tuples.XqmoreYychecks q+q checksXY[(more)qXX# Multiply tuple.XqtotalYychecks q*q 3XY[(total)XXqXX(10, 20, 30, 10, 20, 30)X(10, 20, 30, 10, 20, 30, 10, 20, 30)qXXq# MaxYVmin YwYPs.XqfriendsYy(qKsandyKq, qKmichaelKq, qKaaronKq, qKstacyKq)XXY[(qmaxq(friends))XY[(qminq(friends))qXX# MaxYVmin YwYEs.XqearningsYy(1000, 2000, 500, 4000)XXY[(qmaxq(earnings))XY[(qminq(earnings))XXqXXstacyXaaronX4000X500qXXpairYy(qKdogKq, qKcatKq)qXX# Search Ywa Yh.Xqif qKcatKq qinq pair:XNY[(qKCat foundKq)qXX# Search Ywa Yh not present.Xqif qKbirdKq qnot inq pair:XNY[(qKBird not foundKq)XXqXXCat foundXBird not foundqXXYhsYy(1, 3, 5, 7, 9, 11, 13)qXX# Copy the tuple.XqY[(Yhs[q:q])qXX# Copy all Yhs at index 1 or more.XqY[(Yhs[q1:q])qXX# Copy one Yh, starting at first.XqY[(Yhs[q:1q])qXX# Copy Yhs from index 2Yj4.XqY[(Yhs[q2:4q])XXqXX(1, 3, 5, 7, 9, 11, 13)X(3, 5, 7, 9, 11, 13)X(1,)X(5, 7)qXXq# Three-item tuple.XqitemsYy(qKcatKq, qKdogKq, qKbirdKq)qXX# Ykindex of Y8 with Yh KdogK.XqindexYyitems.qindexq(qKdogKq)XY[(index, items[index])XXqXX1 dogqXXYhsYy(1, 2, 2, 3, 3, 3)XY[(Yhs.qcountq(1))XY[(Yhs.count(3))qX# There are no 100 Yhs, so this YKs 0.XqY[(Yhs.count(q100q))XXqXX1X3Xq0qXXq# A tuple with two YEs.XqpairYyq(1, 2)qXX# CY_ a dY-.X# YlUse the tuple as a key.XqdictYy{}Xdict[pair]YyqKPythonKqXX# Access the dY- YDa tuple.XqY[(dict[q(1, 2)q])XXqXXPythonqXXq# Tuple containing unsorted odd YEs.XqoddsYy(9, 5, 11)qXX# CYNYjYnYVsort.XqYnYyqYnq(odds)XYn.sort()XY[(Yn)qXX# CYN backYjtuple.Xqsorted_oddsYyqtupleq(Yn)XY[(sorted_odds)XXqXX[5, 9, 11]X(5, 9, 11)qXXYhsYy[qKmeowKq, qKbarkKq, qKchirpKq]qXX# Use enumerate on Yn.XqYwpairYpqenumerateq(Yhs):qXN# The pair is a 2-tuple.XNqY[(pair)qXX# Unpack enumerate's YMsYpY|-loop.XqYwindex, YhYpqenumerateq(Yhs):qXN# We have already unpacked the tuple.XNqY[(str(index)Y}qK...KqY}Yh)XXqXX(0, 'meow')X(1, 'bark')X(2, 'chirp')X0...meowX1...barkX2...chirpqXXYhYyqKabcdefghKqXpairsYy[]qXX# YWover YP.X# YlUse step of 2Yprange built-in.X# YlExtract pairs of letters Yzo a Yn of tuples.XqYwiYpqrangeq(1, len(Yh), 2):XNoneYyYh[i - 1]XNtwoYyYh[i]XNpairs.qaYeq((one, two))qXX# Y= Yn of tuple pairs.XqYwqpairqYppairs:XNY[(pair)XXqXX('a', 'b')X('c', 'd')X('e', 'f')X('g', 'h')qXXleftYyqKcatKqXrightYyqKdogKqXY[(qKLEFTKq, left)XY[(qKRIGHTKq, right)XXY[(qK:::FLIP:::Kq)qX# Use tuple unpackingYjflip variables.Xqleft, rightYyright, leftXXY[(qKLEFTKq, left)XY[(qKRIGHTKq, right)XXqXXLEFT catXRIGHT dogXq:::FLIP:::qXLEFT dogXRIGHT catqXXY;timeXXpairYy(1, 2)XXY[(time.time())qXX# Version 1: unpack tuple.XqiYy0XYR i < 10000000:XN(a, b)YypairXNiYyiY}1XXY[(time.time())qXX# Version 2: assign variablesYjtuple separately.XqiYy0XYR i < 10000000:XNaYypair[0]XNbYypair[1]XNiYyiY}1XXY[(time.time())XXqResultsqXX1345673733.21X1345673737.12 (Unpack: q3.91 sq)X1345673742.12 (Assign: q5.00 sq)q

0.-1f9[/\UUi7Y^/0creates tuplesassigns tupleassigns variablestuples, no parenthesesadds and multiples tuplesmax and minsearches tuplestuple slicesindexcounttuples as dictionary keysconverts tuple and listenumeratelist of tuplesflips variablesbenchmarks tuple