Jump to content

Python Programming/Tuples

From Wikibooks, open books for an open world


A tuple in Python is much like a list except that it is immutable (unchangeable) once created. A tuple of hashable objects is hashable and thus suitable as a key in a dictionary and as a member of a set.

Overview

[edit | edit source]

Tuples in Python at a glance:

tup1=(1,'a')tup2=1,'a'# Brackets not neededtup3=(1,)# Singleton tupletup4=1,# Singleton tuple without bracketstup5=()# Empty tuplelist1=[1,'a']it1,it2=tup1# Assign items by "value unpacking"print(tup1==tup2)# Trueprint(tup1istup2)# Falseprint(tup1==list1)# Falseprint(tup1==tuple(list1))# Trueprint(list(tup1)==list1)# Trueprint(tup1[0])# First memberforitemintup1:print(item)# Iterationprint((1,2)+(3,4))# (1, 2, 3, 4)print(tup1*2)# (1, 'a', 1, 'a')tup1+=(3,)# Tuple and string concatenation work similarlyprint(tup1)# (1, 'a', 3), despite immutability *# * From docs: "For immutable targets such as strings, numbers, and tuples,# the updated value is computed, but not assigned back to the input variable."print(len(tup1))# Item countprint(3intup1)# Membership - Truetup6=([1,2],)tup6[0][0]=3print(tup6)# The list referred to by a tuple remains mutableset1=set((1,2))# Can be placed into a set#set1 = set( ([1,2], 2) ) # Error: The list within makes it unhashabledeffoo():return6,9# Return multiple values, as a tupler1,r2=foo()# Receive multiple valuesprint(f'r1 is {r1}, r2 is {r2}')

Tuple notation

[edit | edit source]

Tuples may be created directly or converted from lists. Generally, tuples are enclosed in parentheses.

>>>l=[1,'a',[6,3.14]]>>>t=(1,'a',[6,3.14])>>>t(1,'a',[6,3.14])>>>tuple(l)(1,'a',[6,3.14])>>>t==tuple(l)True>>>t==lFalse

A one item tuple is created by an item in parentheses followed by a comma:

>>>t=('A single item tuple',)>>>t('A single item tuple',)

Also, tuples will be created from items separated by commas.

>>>t='A','tuple','needs','no','parens'>>>t('A','tuple','needs','no','parens')

Packing and Unpacking

[edit | edit source]

You can also perform multiple assignment using tuples.

>>>article,noun,verb,adjective,direct_object=t#t is defined above>>>noun'tuple'

Note that either, or both sides of an assignment operator can consist of tuples.

>>>a,b=1,2>>>b2

The example above: article, noun, verb, adjective, direct_object = t is called "tuple unpacking" because the tuple t was unpacked and its values assigned to each of the variables on the left. "Tuple packing" is the reverse: t=article, noun, verb, adjective, direct_object. When unpacking a tuple, or performing multiple assignment, you must have the same number of variables being assigned to as values being assigned.

Operations on tuples

[edit | edit source]

These are the same as for lists except that we may not assign to indices or slices, and there is no "append" operator.

>>>a=(1,2)>>>b=(3,4)>>>a+b(1,2,3,4)>>>a(1,2)>>>b(3,4)>>>a.append(3)Traceback(mostrecentcalllast):File"<stdin>",line1,in?AttributeError:'tuple'objecthasnoattribute'append'>>>a(1,2)>>>a[0]=0Traceback(mostrecentcalllast):File"<stdin>",line1,in?TypeError:objectdoesnotsupportitemassignment>>>a(1,2)

For lists we would have had:

>>>a=[1,2]>>>b=[3,4]>>>a+b[1,2,3,4]>>>a[1,2]>>>b[3,4]>>>a.append(3)>>>a[1,2,3]>>>a[0]=0>>>a[0,2,3]

Tuple Attributes

[edit | edit source]

Length: Finding the length of a tuple is the same as with lists; use the built in len() method.

>>>len((1,2,3))3>>>a=(1,2,3,4)>>>len(a)4

Conversions

[edit | edit source]

Convert list to tuples using the built in tuple() method.

>>>l=[4,5,6]>>>tuple(l)(4,5,6)

Converting a tuple into a list using the built in list() method to cast as a list:

>>>t=(4,5,6)>>>list(t)[4,5,6]

Dictionaries can also be converted to tuples of tuples using the items method of dictionaries:

>>>d={'a':1,'b':2}>>>tuple(d.items())(('a',1),('b',2))

Uses of Tuples

[edit | edit source]

Tuples can be used in place of lists where the number of items is known and small, for example when returning multiple values from a function. Many other languages require creating an object or container to return, but with Python's tuple assignment, multiple-value returns are easy:

deffunc(x,y):# code to compute x and yreturnx,y

This resulting tuple can be easily unpacked with the tuple assignment technique explained above:

x,y=func(1,2)

Using List Comprehension to process Tuple elements

[edit | edit source]

Occasionally, there is a need to manipulate the values contained within a tuple in order to create a new tuple. For example, if we wanted a way to double all of the values within a tuple, we can combine some of the above information in addition to list comprehension like this:

defdouble(T):'double() - return a tuple with each tuple element (e) doubled.'returntuple([e*2foreinT])

Exercises

[edit | edit source]
  1. Create the list ['a', 'b', 'c'], then create a tuple from that list.
  2. Create the tuple ('a', 'b', 'c'), then create a list from that tuple. (Hint: the material needed to do this has been covered, but it's not entirely obvious)
  3. Make the following instantiations simultaneously: a = 'a', b=2, c='gamma'. (That is, in one line of code).
  4. Create a tuple containing just a single element which in turn contains the three elements 'a', 'b', and 'c'. Verify that the length is actually 1 by using the len() function.
[edit | edit source]
close