--- canonical_url: https://www.scaler.com/topics/tuples-in-python/ title: Tuples in Python | Python Tuples with Examples - Scaler Topics description: Learn about Truples in Python by Scaler Topics. Python tuples are a collection of elements of any data types just like lists, but tuples are immutable. author: Rajpreet Nayyar category: Python amphtml: https://www.scaler.com/topics/tuples-in-python/amp/ publish_date: 2021-11-29 --- :::section{.abstract} Tuples in python is one of the four inbuilt data types used to store collections in Python. Unlike other data types, the elements in tuples are ordered and immutable. They are used to store multiple items in a single variable and provides some built-in operation to work with them. ::: :::section{.main} ## Creating a Tuple in Python Tuples in python can only be created when they are being assigned, hence by placing all the elements inside parenthesis, separated by a comma will create a tuple. Let’s take a closer look at the syntax: ```python tempTuple = ('apple', 'mango', 'banana') print(tempTuple) ``` **Output** ```python ('apple', 'mango', 'banana') ``` The parenthesis in the above syntax are optional and hence a tuple can also be created without writing the parenthesis. But remember it’s always a good practice to have the parenthesis, as it always increases the code readability and understanding. The above snippet can also be written as: ```python tempTuple = 'apple', 'mango', 'banana' print(tempTuple) ``` **Output** ```python ('apple', 'mango', 'banana') ``` ::: :::section{.main} ## Immutable in Tuples Tuples in Python are similar to lists but with a key difference: they are immutable. This means once a tuple is created, its elements cannot be changed, added, or removed. Let's break down some characteristics of tuples: * Immutable Nature: Once a tuple is created, its elements cannot be modified. This ensures data integrity and stability. * Ordered Collection: Like lists, tuples maintain the order of elements as they are inserted. * Support for Duplicate Values: Tuples allow duplicate values just like lists. * Accessing Elements: Elements in a tuple can be accessed using their index values. Here's an example illustrating the immutability of tuples in python: ```python my_tuple = (1, 2, 3) #Attempting to change an element in the tuple will result in an error my_tuple[1] = 1 # This will raise a TypeError ``` When attempting to modify an element within a tuple, Python will raise a TypeError because tuples in python do not support item assignment due to their immutable nature. This constraint ensures that once data is stored in a tuple, it remains unchanged throughout the program's execution. ::: :::section{.main} ## Python Tuple Types Python offers two primary types of tuples: named tuples and unnamed tuples. * **Named tuples:** created by subclassing the tuple class and assigning a name to the new class, serve well for representing structured data like records, akin to database entries. Each element within a named tuple corresponds to a field in the record, permitting access by name instead of index. For instance: ```python class MyTuple(tuple): pass my_tuple = MyTuple(("one", "two", "three")) print(my_tuple.one) ``` **Outputs** ``` one ``` * **Unnamed Tuples:** are more prevalent and are generated simply by separating values with commas. They are suitable for storing unstructured data that doesn't necessitate naming. Here's an example: ```python my_tuple = (1, 2, 3) print(my_tuple) ``` **Outputs** ``` (1, 2, 3) ```` In this instance, a tuple in python containing three elements is created. Accessing elements within the tuple can be achieved using index notation, akin to how one would interact with a list. ::: :::section{.main} ## Accessing Elements in a Python Tuple and Indexing: Accessing elements in a tuple is no different then accessing elements in a list. As python follows 0 based indexing hence a tuple with n elements will have indices from 0 through n-1. An index in a tuple is accessed with the index operator `[ ]`. For example: Let’s consider a basic tuple: ```python tempTuple = ('hello', 1, 2, 3) print(tempTuple[0]) # prints first element of the tuple print(tempTuple[3]) # prints last element of the tuple print(tempTuple[4]) # error ``` ::: :::section{.main} ### Nested Python Tuple Accessibility: ```python nestedTuple = ('hello', [1 ,2, 3], (4, 5, 6)) print(nestedTuple[0][2]) print(nestedTuple[2][2]) ``` ::: :::section{.main} ### Accessing Via Negative Indices: Python allows you to access elements of a collection via negative indices. When accessing using a negative index, `-1` depicts the last element and `-n` depicts the first index where n is the length of the index. Consider the following mapping of positive index with negative index: ![accessing tuples via negative indices](https://scaler-topics-articles-md.s3.us-west-2.amazonaws.com/accessing-tuples-via-negative-indices.webp) ```python tempTuple = ('Welcome', 'to', 'interview', 'bit.', 'Have', 'a', 'great', 'day') print(tempTuple[2]) # interview print(tempTuple[-6]) # interview ``` ::: :::section{.main} ## Updating Tuples in Python Adding a new element or deleting one is not really an option when dealing with tuples in python, as they are immutable. Even the elements of the tuple cannot be updated until and unless the element is mutable for example a list. Let’s take an example ```python tempTuple = ('Welcome', 'to', 'interview', 'bit.', 'Have', 'a', 'great', 'day', [1, 2, 3]) # tempTuple[0] = 'Hello' # throws type error, tuple object does not support type assignment. tempTuple[8].append(4) # appending a new integer i.e. 4 in a list at 8th index of the tuple ‘tempTuple’ # Printing the list at 8th index in the tuple print(tempTuple[8]) # OUTPUT: [1, 2, 3, 4] tempTuple[8].pop(3) # popping element at 3rd index from the list i.e. 8th index of the tuple 'tempTuple' # Printing the list at 8th index in the tuple print(tempTuple[8]) # OUTPUT: [1, 2, 3] tempTuple = (1, 2, 3) # Assigning tuple all over again # Printing the tuple print(tempTuple) # OUTPUT: (1, 2, 3) ``` **Output** ```python [1,2,3,4] [1,2,3] (1,2,3) ``` Tuples in python can definitely be reassigned, which is very different from updating a tuple. Reassigning a tuple is redefining the tuple all over again. Just like strings, we can also concat two or more tuples to form a new tuple using `‘+’` operation or apply repetition on a tuple using `‘*’` operator, just the result here is a python tuple and not a string. ```python # concatenating two different tuples print(('apple', 'mango') + (1, 2, 3)) # OUTPUT: (‘apple’, ‘mango’, 1, 2, 3) # repeat a tuple 5 times print(("apple",) * 5) # OUTPUT: (‘apple’, ‘apple’, ‘apple’, ‘apple’, ‘apple’) ``` **Output** ```python ('apple', 'mango', 1, 2, 3) ('apple', 'apple', 'apple', 'apple', 'apple') ``` ::: :::section{.main} ## In-built Functions for Tuple Python has the following inbuilt functions to offer for tuples: ![slicing in python tuples](https://scaler-topics-articles-md.s3.us-west-2.amazonaws.com/slicing-in-python-tuples.webp) ::: :::section{.main} ## Different Operations Related to Tuples * **Concatenation**: We will use plus operators(+) to Concatenation of Python Tuples. ```python tempTuple = ('apple', 'mango') result = tempTuple + (1, 2, 3) # concatenating two different tuples print('concatenation of a tuple', result) # OUTPUT: concatenation of a tuple (‘apple’, ‘mango’, 1, 2, 3) ``` * **Nesting**: We can do the nesting of tuples means a tuple inside another tuple.``` ```python # Code for creating nested tuples tup1 = ('a','b','c') tup2 = ('d','e') tup3 = (tup1, tup2) print(tup3) #(('a','b','c'), ('d','e')) ``` * **Repetition**: We have the ability to form a tuple containing multiple identical elements by duplicating a single element within that tuple. ```python tup = ('2',)*3 print(tup) #output: ('2','2','2') ``` * **Slicing**: Slicing in tuples works the same as it works for a [String slicing](https://www.scaler.com/topics/string-slicing-in-python/) or any other sequence of elements. Slice is an operator that allows you to fetch a sub collection (in this case a sub tuple) from a collection by slicing it from a start index and a stop index. **Slice syntax:** > **tuple[start : stop : step]** * **start:** is the starting index of the string, on which slicing operation has to be performed. It determines from where slicing of the string will ‘begin’. * **stop:** is the stopping index of the slicing, ‘until’ which slicing operation has to be performed i.e stop index is excluded while generating the sub-tuple. * **step:** It is an optional argument that defines the steps when iterating the list i.e. it allows us to skip over elements. Consider the above figure when understanding the following code snippet ```python temptuple = ("Welcome", "to", "interview", "bit.", "Have", "a", "great", "day") tuple1 = temptuple[::] # fetching complete tuple print("tuple1:", tuple1) # OUTPUT: (‘Welcome’, ‘to’, ‘interview’, ‘bit.’, ‘Have’, ‘a’, ‘great’, ‘day’) tuple2 = temptuple[0 : 6] # fetching tuple from 0th index to 6th index print("tuple2:", tuple2) # OUTPUT: (‘Welcome’, ‘to’, ‘interview’, ‘bit.’, ‘Have’, ‘a’) tuple3 = temptuple[:: 3] # jumping every third element from start to end print("tuple3:", tuple3) # OUTPUT: (‘Welcome’, ‘bit.’, ‘great’) tuple4 = temptuple[1:5:2] # jumping to every 2nd element starting from 1st index until 5th index print("tuple4:", tuple4) # OUTPUT: (‘to’, ‘bit.’) tuple5 = temptuple[-8:-5] # 8th index from end to 5th index from end print("tuple5:", tuple5) # OUTPUT: (‘Welcome’, ‘to’, ‘interview’) tuple6 = temptuple[::-3] # jumping every 3rd element in reverse print("tuple6:", tuple6) # OUTPUT: (‘day’, ‘Have’, ‘to’) tuple7 = temptuple[-7:-3:2] # alternate implementation of tuple4 print("tuple7:", tuple7) # OUTPUT: (‘to’, ‘bit.’) ``` **Output** ```python tuple1: ('Welcome', 'to', 'interview', 'bit.', 'Have', 'a', 'great', 'day') tuple2: ('Welcome', 'to', 'interview', 'bit.', 'Have', 'a') tuple3: ('Welcome', 'bit.', 'great') tuple4: ('to', 'bit.') tuple5: ('Welcome', 'to', 'interview') tuple6: ('day', 'Have', 'to') tuple7: ('to', 'bit.') ``` * **Deleting**: As discussed, python tuples being immutable cannot be updated. Hence once some values are assigned to a tuple, it cannot be deleted. You can delete a tuple as a whole, but deleting a specific value/element in a tuple is not possible. ```python tempTuple = (1, 2, 3, 4, 5) # tempTuple.pop() # throws error as object has no attribute pop # del tempTuple[3] # throws error as tuple does not support object deletion print(tempTuple) # OUTPUT: (1, 2, 3, 4, 5) del tempTuple print(tempTuple) # throws NameError: name 'tempTuple' is not defined ``` **Output** ```python (1,2,3,4,5) Traceback (most recent call last): File "main.py", line 6, in <module> print(tempTuple) # throws NameError: name 'tempTuple' is not defined NameError: name 'tempTuple' is not defined ``` * **Finding the length**: In Python, determining the length of a tuple can be accomplished using the built-in function len(). Simply provide the tuple as an argument to len(). This will return the number of elements contained within the tuple. ```python tup = (1,2) print(len(tup)) #Output: 2 ``` * **Multiple Data Types with tuples**: Tuples in Python are versatile containers, allowing you to store elements of different data types within the same tuple. ```python temp = ("a",True,2) print(temp) #Output: ('a',True,2) ``` * **Conversion of lists to tuples**: In Python, you can transform a list into a tuple effortlessly by utilizing the tuple() constructor and providing the list as its argument. ```python list1 = [1, 2, 3] print(tuple(list1)) #Output: (1, 2, 3) ``` * **Tuples in a Loop**: We can also create a tuple with a single element in it using loops. ```python temp = ('a',) n = 2 for i in range(int(n)): temp = (temp,) print(temp) ``` **Output**: ``` (('a',),) ((('a',),),) ``` ::: :::section{.main} ## Advantages and Disadvantages of Tuple in Python ### Advantages: * Tuples being immutable, turns out to be a write-protected collection. Tuples can be of advantage when we want to store some secure read only data that we cannot afford to be changed throughout our code. * Tuples can store data of multiple data types, that makes them a heterogeneous collection. * Tuple being a readonly collection, has a faster iteration. (As they are stored in a single block of memory, and don’t have extra space for storing objects, they have constant set of values) ### Disadvantages: * Tuple’s being write protected, is an advantage but also a disadvantage as it cannot be used when we want to add or delete a specific element. Hence has a limited use case. * Syntactically less readable as, tuples can be created by either adding parentheses or by not providing them incase we have more than one element. But not using parentheses in case of one element, will not create a tuple and hence a trailing comma in such case is required. This can makes code readability a bit complex for some. * As tuple is a class, it's stored on the heap and is overhead on the garbage collector. Tuple’s advantages and disadvantages are nothing but its use cases i.e. tuple serves some use cases hence one should know when to use tuple, in order to use it for their advantage. Tuples when used where a list or a dictionary or a set would’ve been used, will turn out to be a disadvantage. ::: :::section{.summary} ## Conclusion: 1. Tuples support integer-based indexing and duplicate elements, enhancing data organization and retrieval. 2. They can be defined with or without parentheses; however, a trailing comma is necessary without parentheses to signify a tuple. 3. Optimal use of tuples depends on their intended application; misapplication can lead to inefficiencies, such as substituting for lists, sets, or dictionaries. 4. Choosing the appropriate data structure requires careful consideration of use cases to ensure efficient data handling and manipulation. :::