0% found this document useful (0 votes)
171 views

Tuple Notes PDF

Uploaded by

vsnpradeep
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
171 views

Tuple Notes PDF

Uploaded by

vsnpradeep
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 16
Tuple Python Tuples are like a list. It can hold a sequence of items. The difference is that it is immutable, tuple is an ordered collection of elements which is immutable (cannot be changed i.e., unchangeable) and it allows duplicate elements. It also supports indexing So a tuple is a container which can hold a series of comma-separated values (items or elements) between parentheses Tuples are immutable i.e. you cannot change its content once itis created and it can hold items of different data types (can contain heterogeneous elements). Tuples may contain objects of different types like Integer, Float, String, Boolean, nested Tuples, Lists or other objects Tuples are sequences, just like lists and strings. Tuples are also iterable objects so that you can iterate or loop or fetch through each element item one at a time in the tuple. In some ways a tuple is similar to alist in terms of indexing, slicing, concatenation, repetition, membership and nested objects. ‘The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples Use parentheses, whereas lists use square brackets. Characteristics of Tuple The important characteristics of Python Tuples are as follows: (2) Tuples are ordered. (2) Tuples can contain elements or objects of any type (3) Tuples elements can be accessed by index. (4) Tuples can be nested to arbitrary depth. (5) Tuples are immutable. (6) Tuples are fixed or static Tuples are ordered. The tuple preserves the insertion order of the elements. It simply means if you ut objects in a certain order and they will remain in that same order. The items will show up in the order in which you insert or put them in the list while displaying the tuple. Creating a tupl ‘We can have tuple of same type of data items as well as mixed type of data items as well as we can have duplicate elements. To create a tuple, just put alist of values separated by commas within parenthesis. Creating a tuple is as simple as putting different comma-separated values between parentheses. ‘tupl = (10, 20, 30, 40, 50) tup2 = ("maths", 80, "physics", 75, "chemistry", 70) ‘The parentheses are optional, you can simply create a tuple by putting different comma-separated values like ‘tup3 = 80, 90, 70, 20, 30, 40, 60/0" Creating empty tuple: The "empty" tuple is just an empty pair of brackets. An empty tuple can be created with empty parentheses (opening and closing brackets containing nothing inside it) tuple_data = () Tuple with only single element: ‘When a tuple has only one element, we must put a comma after the element, otherwise Python will not treat it as a tuple, tuple_data = (36,) If we do not put comma after 36 then python will treat data as an int variable rather than a tuple. How to access tuple elements ‘We use indexes to access the elements of a tuple. Individual elements in a tuple can be accessed using an index inside the square brackets [] (indexing operator) List Index ‘We can use the index operator [] to access an item in a list. Indexes starts with 0 that is why we use Oto access the first element of tuple, 1 to access second element and so on. Note: 1. Type rror: If you do not use integer indexes in the tuple. For example my_data[2.0] will raise this error. The index must always be an integer. 2. IndexError: Index out of range. This error occurs when we mention the index which is not in the range. For example, if a tuple has 5 elements and we try to access the 7th element then this error would occur. Negative indexes in tuples Similar to lst and strings we can use negative indexes to access the tuple elements from the end. “1 to access last element, -2 to access second last and so on. erating a tuple You can iterate through the tuple using for..in loop # tuple of fruits fruit_tuple = ("Pear", "Watermelon", "Cheeku", "Strawberry”,"Apple", "Orange") # iterating over tuple elements for fruit in fruit_tuple: print(fruit) Nested Tuples Anested tuple is a list that appears as an element in another tuple. ‘Atuple becomes nested when itis stored inside another tuple. Nesting can be done with tuples, lists or dictionaries. It simply means that you can put tuples in tuples, or lists in lists, dictionaries in dictionaries or even tuples inside of lists and so on. Nesting can be done infinitely, you can have a tuple that contains a tuple with a tuple inside of it, another tuple inside of that tuple and so on. Nesting can easily be done by utilizing a Loop that, allows you to iterate and either extract or place other items inside of the tuples. We use the double indexes are used to access the elements of nested tuple. The first index represents the element of main tuple and the second index represent the element of the nested tuple. How to access elements from nested tuple nested = ("hello", 2.0, 5, (10, 20)) innertuple = nested(3) print(innertuple) item = innertuple(2} print(tem) print(nested[3][1]) In this tuple, the element with index 3 is a nested tuple. If we print(nested[3]}, we get [10, 20] To extract an element from the nested tuple, we can proceed in two steps. First, extract the nested tuple, then extract the item of your interest. Itis also possible to combine those steps using bracket operators that evaluate from left to right like nested[3][1]) We use the double indexes are used to access the elements of nested tuple. The first index represents the element of main tuple and the second index represent the element of the nested tuple, data = (236,'Gouthami’(80,95,96,94,92,88)) print(datal21(1)) For example data(2][1J, is used to access the second element of the nested tuple. Because 2 represents the third element of main tuple which is a tuple and then 1 represents the second element of that sub tuple. Output of data[2][1] = 95 Operations that can be performed on tuple in Python: ‘Append operation on tuple ‘We cannot add or append new elements to a tuple because tuple is an immutable object ing elements of tuple ‘We cannot change the elements of a tuple because elements of tuple are immutable. However we can change the elements of nested items that are mutable, Delete operation on tuple We already discussed above that tuple elements are immutable which also means that we cannot delete the elements of a tuple. However deleting entire tuple is possible. Slicing operation in tuples ‘The slicing operation is used by specifying the name of the sequence followed by an optional pair of numbers separated by a colon within square brackets. Note that this is very similar to the indexing operation you have been using till now. Remember the numbers are optional but the colon isn't. The first number (before the colon) in the slicing operation refers to the position from where the slice starts and the second number (after the colon) indicates where the slice will stop at. Ifthe first number is not specified, Python will start at the beginning of the sequence. If the second number is left out, Python will stop at the end of the sequence. Note that the slice returned starts at the start position and will end just before the end position i.e. the start position is included but the end position is excluded from the sequence slice. shoppingtuple = ("Sugar","Salt","Rice", "Bread", "Butter”,"Jam","Milk","Wheat") ‘Thus, shoppingtuple [1:3] returns a slice of the sequence starting at position 1, includes position 2 but stops at position 3 and therefore a slice of two items is returned. Similarly, shoppingtuple [:] returns a copy of the whole sequence. You can also do slicing with negative positions. Negative numbers are used for positions from the end of the sequence. For example, shoppingtuple [:-1] will return a slice of the sequence which excludes the last item of the sequence but contains everything else. You can also provide a third argument for the slice, which is the step for the slicing (by default, the step size is 1). shoppingtuple (0:7:2] my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99) print(my_data) elements from 3rd to Sth # prints (33, 44, 55) print(my_data[2:5]) elements from start to 4th 4H prints (11, 22, 33, 44) print(my_data[:4]) elements from Sth to end # prints (55, 66, 77, 88, 99) print{my_datal4:)) elements from Sth to second last # prints (55, 66, 77, 88) print(my_dataf4:-1)) # displaying entire tuple print(my_data[:]) Membership Test in Tuples in: Checks whether an element exists in the specified tuple. not in: Checks whether an element does not exist in the specified tuple. my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99) print(my_data) true print(22 in my_data) false print(2 in my_data) # false print(88 not in my_data) true print(101 not in my_data) 1) You can't add elements to a tuple. Tuples have no append or extend or insert method, 2) You can't remove elements from a tuple. Tuples have no remove or pop method. 3) You can find elements in a tuple, since this doesn’t change the tuple. 4) You can also use the in operator to check if an element exists in the tuple or an element not exists in the tuple. Tuple vs List ‘Tuples are fixed size in nature whereas lists are dynamic. In other words, a tuple is immutable whereas a list is mutable. 1. The elements of a list are mutable whereas the elements of a tuple are immutable. 2. When we do not want to change the data over time, the tuple is a preferred data type whereas when we need to change the data in future, list would be a wise option. 3. Iterating over the elements of a tuple is faster compared to iterating over a list. 4, Elements of a tuple are enclosed in parenthesis whereas the elements of list are enclosed in square bracket. Advantages of choosing tuples over Lists (i) Tuples are faster than lists. If you're defining a constant set of values and if you want to iterate ‘through it, then use a tuple instead of alist. (iit makes your code safer if you use tuple as it is "write-protect” data that does not need to be changed. (ii) Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values like strings, numbers, and other tuples). Lists can never be used as dictionary keys, because lists are not immutable. Packing and Unpacking Tuple How multiple assignment works in Python: Multiple assignment is also known as tuple unpacking or iterable unpacking that allows you to assign ‘multiple variables at the same time in one line of code. The words multiple assignment, tuple unpacking, and iterable unpacking interchangeably. They're all just different words for the same thing Python's multiple assignment looks like this: x=10 Here we're setting x to 10 and y to 20. ‘What's happening at a lower level is that we're creating 2 tuple of 10, 20 and then looping over that ‘tuple and taking each of the two items we get from the looping and assigning them to x and y in order. This syntax might make that a bit clearer: (x,y) = (10, 20) Parenthesis are optional around tuples in Python and they're also optional in multiple assignment (which uses a tuple-like syntax). All of these are equivalent: x,y= 10, 20 x, y= (10, 20) (%, y) = 10, 20 (x, y) = (10, 20) Multiple assignment is often called “tuple unpacking” because it’s frequently used with tuples. But we can use multiple assignment with any iterable, not just tuples. Here we're using it with a list: x, ¥ = [10, 20] print(x) 10 printy) 20 And with a string: print(x) Wt print{y) ‘Anything that can be looped over can be “unpacked” with tuple unpacking / multiple assignment. Here's another example to demonstrate that multiple assignment works with any number of items and that it works with variables as well as objects we've just created: print(x, y, 2) 102030, (x, ¥, 2) = (2, ¥, x) print(x, y, 2) 302010 Note that on that last line we're actually swapping variable names, which is something multiple assignment allows us to do easily. Packing and Unpacking a Tuple ‘Tuples in Python are values separated by commas. Enclosing parentheses for inputting tuples are optional, so the two assignments a=1,2,3 #aisthe tuple (1, 2,3) and a= (1, 2,3) # ais the tuple (1, 2, 3) are equivalent. ‘The assignment a= 1, 2, 3 is also called packing because it packs values together in a tuple In Python there is a very powerful tuple assignment feature that assigns right hand side of values into left hand side. In other way it is called unpacking of a tuple of values into a variable. ‘To unpack values from a tuple and do multiple assignments use unpacking AKA multiple assignment x, ¥,2= (1, 2,3) fixes Hy fz In packing, we put values into a new tuple while in unpacking we extract those values into a single variable. Packing and unpacking in Python # these lines PACKS values into variable a a= ("Gouthami","GRVIT Hyderabad", "Engineering") # these lines UNPACKS values of variable a (student,college, type_ofcollege) = a # print name of student print(student) 4 print college name print{college) # print type of college print(type_ofcollege) NOTE : In unpacking of tuple number of variables on left hand side should be equal to number of values which are inside the given tuple Disposable variable name ‘The symbol "_" (underscore) can be used as a disposable variable name if one only needs some elements of a tuple, acting as a placeholder: 2,3,4 Optional arguments (*args) for unpacking tuple Python uses a special syntax to pass optional arguments (*args) for tuple unpacking, This means that there can be many number of arguments in place of (*args) in Python. All values will be assigned to every variable on left hand side and all remaining values will be assigned to *args, x, "y,2= (100, "Zend", "of", "Python", 500) # print details print(x) printly) print(2) 4 first and second will be assigned to x and y and remaining will be assigned to 2 x,¥,*2= (100, "Zend", "python", 500) print(x) print(y) print(z) Python Tuples Packing You can also create a Python tuple without parentheses. This is called tuple packing. b= 1, 2.0, ‘three! Python Tuples Unpacking Python tuple unpacking is when you assign values from a tuple to a sequence of variables in python. Percentages=(99,95,90,89,93,96) a,b,c,de,fepercentages c 90 But when you do so with just one element, it may create some problems. a-(1) ‘type(a) a=(1,) ‘type(a) Tuple functions a.ten() The len() function returns its length. my_tuple = (10, 20, 30, 40, 50) print(len(my_tuple)) 5 datatuple = (1, 2, 3, [6,5]) 4 Itreturned 4, not 5, because the list counts as 1, b. max() It returns the item from the tuple with the highest value. my_tuple 10, 20, 30, 40, 50) print(max(my_tuple)} 50 datatuple = (1, 2, 3, [6, 51) max(datatuple) ‘We cannot apply this function on the tuple datatuple, because integers cannot be compared to a list Let's try that on strings max(('Hi'hi'Hello’)) ‘tit ‘hi’ is the greatest out of these, because h has the highest ASCII value among ‘h' and 'H But you can't compare an int and a string ‘Typetrror: '>' not supported between instances of ‘int’ and 'str’ cc. min() Like the max() function, the min() returns the item with the lowest value. my_tuple = (10, 20, 30, 40, 50) print(min(my_tuple)) 10 d. sum() This function returns the arithmetic sum of all the items in the tuple. x= (6,8, 4, 10, 12, 18, 24, 36, 2) print(sum(x)) However, you can't apply this function on a tuple with strings. sum(('1','2",'3')) ‘Typetrror: unsupported operand type(s) for +: ‘int’ and ‘ste’ e.any() This function returns True if any one item in the tuple has a Boolean value of True, then . Otherwise, it returns False. sample_tuple = (False, False, False, True, False, False, False) print(any(sample_tuple)) True sample_tuple = (",0,False,’ print(any(sample_tuple)) True ‘The string ‘0' does have a Boolean value of True. If it was rather the integer 0, it would've returned False, sample_tuple = (",0,False,"",0,") print(any(sample_tuple)) False fall) Unlike any(),all() returns True only if all tems have a Boolean value of True. Otherwise, it returns False. print(all(('1',True,-1,'0")) True print(all(('1',,True,-1,0))) False 8. sorted() This function returns a sorted list from the given iterable. It sorts the elements of a given iterable in a specific order - Ascending or Descending. Syntax: sorted(iterable(, key][, reverse]) Parameters: (i) iterable: sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any iterator (ii) reverse (optional): If true, the sorted list is reversed (or sorted in Descending order). By default it will sort in Ascending order is not provided (ii) key (optional) : function that serves as a key for the sort comparison Return value: sorted() method returns a sorted list from the given iterable. ‘e', ‘a’, ‘u', 'o!, i) pytuple print(sorted{pytuple)) (a,'e',"7,"0%,"4") pyTuple = (75, 25, 36, 10, 50) print(sorted(pyTuple)) (10, 25, 36, 50, 75) Tuple methods a. index(): This method takes one argument and returns the index of the first appearance of an item in a tuple. 1,2,3,2,4,5,2) print(a.index(2)) 1 ‘As you can see, we have 2s at indices 1, 3, and 6. But it returns only the first index. b) count(): ‘This method takes one argument and returns the number of times an item appears in the tuple. (1,2,3,2,4,5,2) a.count(2) 3

You might also like