Page 1 :
Pit Introduction, , 92 Creating and Accessing Tuples, 83 Tuple Operations, , _ g4 Tuple Functions and Methods, , , , INTRODUCTION, , The Python tuples are sequences that are used to store a tuple of values of any type. You have, Jearnt in earlier chapters that Python tuples are immutable i.e., you cannot change the elements, _ of atuple in place ; Python will create a fresh tuple when you make changes to an element of a, tuple. Tuple is a type of sequence like strings and lists but it differs from them in the way that, “lists are mutable but strings and tuples are immutable., ‘This chapter is dedicated to basic tuple manipulation in Python. We shall be talking about, ‘creating and accessing tuples, various tuple operations and tuple manipulations through some, built-in functions., , ages
Page 2 :
0 COMPUTER SCIENCE WITH PYTHON | ‘, , 3.2 CREATING AND ACCESSING TUPLES, , A tuple is a standard data type of Python that can store a sequence of values pelenging to any, type. The Tuples are depicted through parentheses i.e., round brackets, ¢.g., following are some, tuples in Python :, , 0 # tuple with no member, empty tuple, , (1, 2, 3) # tuple of integers, , (1, 2.8, 3.7, 9) # tuple of numbers (integers and floating point) :, Ca’, "bi, 'c’) # tuple of characters, , Ca’, 2, 'b', 3.5, ‘zero') # tuple of mixed value types, , One’, 'Two', ‘Three’) # tuple of strings oe a, , Tuples are Immutable sequences, , Before we proceed and discuss how to create tuples, one thing of Python i.e, you cannot, that must be clear is that Tuples are immutable (i.c., change elements of a tuple in, non-modifiable) i.e., you cannot change elements of a tuple in place., , place, a, , 3.2.1 Creating Tuples, Creating a tuple is similar to list creation, but here you need to put a number of expressions in, parentheses. That is, use round brackets to indicate the start and end of the tuple, and separate, the items by commas. For example :, , (2, 4, 6), , Cabc’, 'def), , (1, 2.0, 3, 4.8), Oo, , Thus to create a tuple you can write in the form given below :, , Te(), , T=(value, ...), , This construct is known as a tuple display construct., Consider some more examples :, , . The Empty Tuple, The empty tuple is ( ). It is the tuple equivalent of 0 or". You can also create an empty tuple as:, , T=tuple(), It will generate an empty tuple and name that tuple as T., , Single Element Tuple, Making a tuple with a single element is tricky because if you just give a single element in round, brackets, Python considers it a value only, e.g.,, >>> t=(1), , dot ,, —— (1) was treated as an integer expression,, 1 hence t stores an integer f, not a tuple
Page 3 :
peooter 8 TUPLES, , , , 261, To construct a tuple wi, th 2, below : one element just add a comma after the single clement “8 shown, poo te,, prt, G) Both these weve will create tuples, >>> t2=(4,), rp t2, (4,), Tuples are formed by placing », 3, Long tuples comma-separated tuple of, e : Jons in parenthese, If a tuple contains many elements, then to enter such long express! = rentheses., , tuples, you can split it across several lines, as given below :, , sars~ (0, 2, &» 9: 16, 25, 36, 49, 64, B1, 108, 121, 144, 169, 196, 225,, + 289, 324, 261, 400, 441, 484, 529, 576, 625 ), , Sa opening parenthesis and closing parenthesis appear just in the beginning and end of, , 4, Nested tuples, , Ifatuple contains an element which is a tuple itself then it is called nested tuple ¢.g., following is, a nested tuple :, , t1=(1, 2, (3, 4)), , The tuple t] has three elements in it: 1, 2 and (3, 4). The third element of tuple t1 isa tuple itself,, hence, t1 is a nested tuple., , Creating Tuples from Existing Sequences, , You can also use the built-in tuple type object (tuple( )) to create tuples from sequences as per, the syntax given below :, , T = tuple(<sequence>), , where <sequence> can be any kind of sequence object including strings, lists and tuples., , Python creates the individual elements of the tuple from the individual elements of passed, sequence. If you pass in another tuple, the tuple function makes a copy., , Consider following examples :, 59 tl = tuple(‘hello’) Tuple :1 is created from another sequence + a string “hello”, >>> tl It generated individual elements from the individual, (hi, ‘eT, ‘Ts 0), , oop be [W, te, ts], , >>> t2=tuple(L) Tuple 2 is created from another sequence - a list L, 55> t2 It generated individual elements from the, (we, 'r', ‘ts 'Y) individual elements of the passed list L
Page 4 :
h = COMPUTER SCIENCE ATH PYTHON — xi, You can use this method of creating tuples of single characters or single digits via keyboard, , input. Consider the code below :, , ti» tuple( input (‘Enter tuple elements:')), , Enter tuple elements : 234567, th Te sae in crea he emer of ete, oe using each of the character pals, , (7,3, 4,567), F arenthesis, it will create a tuple usi, i around input( ), even if you not put P Fl, haga gas as Een But most commonly used method to input Ae ic, evallinput0) as shown below :, , tuple = eval (input ("Enter tuple to be added:*)), , print (“Tuple you entered :", tuple), , when you execute it, it will work somewhat like +, , Enter tuple tobe added: (2, 4, "a", “hJki1" (3,41), Tuple you entered : (2, 4, "a", “njkjl", {3,4]), If you are inputting a tuple with eval( ), then make sure to enclose the tuple elements in, parenthesis., Please note sometimes (not always) eval() does not work in Python shell. At that time, you can, run it through a script too., , 8.2.2 Accessing Tuples, , Tuples are immutable (non-editable) sequences having a progression of elements. Thus, other than, eaitng items, you can do all that you can do with lists. Thus like lists, you can access ifs individual, elements, Before we talk about that, let us learn about how elements are indexed in tuples., , Similarity with Lists, Tuples are very much similar to lists except for the mutability. In other words, Tuples are, immutable counter-parts of lists. Thus, like lists, tuple-elements are also indexed, ie., forward, indexing as 0, 1, 2, 3,... and backward indexing as 1, -2, -3,... [See Fig 8.1(a)], , , , , , , , tuplet = ( ‘a’, uw), findexng > O 1 2 9 4, vom ERE) <O tupiet (21 = 1 = rptet 13), , Sofa? 1 <Gewerindeang] 1 ante] = unio 2], , tuple? [4] = "u" = tuple? [-1], , , , , , , , (a) Tuple Elements’ two way indexing, , , , , , , , , , , , , Tuples are stored in memory exactly strings, except, that because some of their Seearte larger, others, they store a reference at each index, , instead of single character as in strings,, , Each of the individual iter, cqnounere aa Wiener ce en tore, , ~ 17, True, “good”, 459, , , , , , Figure 8.1 (6) How tuples are internally organized
Page 5 :
goto’ B= TUPLES, o, , , , 263, Thus, you can access the ty j, Tuplelil will give you ey, Pie elements, , ato b-1 and so on. Put an at i®, , « Length. Function ten(t), ¢ Indexing and Slicing, Ti] returns the j ., Tli:)) returns a ae at index i (the first item has index 0),, Ti: jn) retums a tuple, containing the objects between i and j excluding index j,, index j. Just like liste UP!® Comaining every nth item from index i to j, excluding, , ¢ Membership opera : ast, work for other wee and ‘not in’ operators work on Tuples just like they, , not in does the opposite, in tells if an element is present in the tuple or not and, , ind Just like you access a list’s or a string’s elements e.g,, Words lex; Tuplefa:b] will give you elements between indexes, » tuples are similar to lists in following ways ', , Teturs the number of items (count) in the tuple T, © Concatenation and Re, end of another. The *, operations in a later, , Plication operators + and *. The + operator adds one tuple to the, operator repeats a tuple. We shall be talking about these two, Section 8.3 - Tuple Operations., , Accessing Individual Elements, , As mentioned, the individual elements of * :, a tuple are accessed through their indexes in, square brackets. Consider the following ex: ails re ac igh given, >>> vowels = (‘a’, 'e’, '1', ‘o', 'u’), >>> vowels[@], , >>> vowels[4], , 4 e accessing tuple etements,, ‘u ke pass in a negative index,, the, >>> vowels[~ 1] ares = eae ~, e | element’s forward index., >>> wowels[~ 5] SS, , Recall that like strings, if you pass in a negative index, Python adds the length of the tuple to the, index to get its forward index. Thats, for a 6-element tuple T, TI-5] will be internally computed as:, , T[-5+6]=T11], and soon., , Difference from Lists, Although tuples are similar to lists in many ways, yet there is an important difference in, mutability of the two. Tuples are not mutable, while lists are. You cannot change individual, elements of a tuple in place, but lists allow you to do so., That is, following statement is fully valid for lists (BUT not for, , tuples). That is, if we have a list L and a tuple T, then, Fuptes are similar to lists in, , L[1] = element many ways like indexing, slicing, , is VALID for Lists. BUT and accessing —_ individual, elements but they are different, , T[i] = element , . ; In the sense that tuples are, , is INVALID as you cannot perform item-assignment in immutable while lists are not., immutable types. ws = Seg RES a : 7