Tuple Operations in Python (original) (raw)
Python Tuple is a collection of objects separated by commas. A tuple is similar to a Python list in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is immutable, unlike the Python list which is mutable.
Python `
Note : In case of list, we use square
brackets []. Here we use round brackets ()
tup = (10, 20, 30)
print(tup) print(type(tup))
`
Output
(10, 20, 30) <class 'tuple'>
What is Immutable in Tuples?
Unlike Python lists, tuples are immutable. Some Characteristics of Tuples in Python.
- Like Lists, tuples are ordered and we can access their elements using their index values
- We cannot update items to a tuple once it is created.
- Tuples cannot be appended or extended.
- We cannot remove items from a tuple once it is created.
Let us see this with an example.
Python `
tup = (1, 2, 3, 4, 5)
tuples are indexed
print(tup[1]) print(tup[4])
tuples contain duplicate elements
tup = (1, 2, 3, 4, 2, 3) print(t)
updating an element
tup[1] = 100 print(tup)
`
**Output:
2
5
(1, 2, 3, 4, 2, 3)
Traceback (most recent call last):
File "Solution.py", line 12, in
t[1] = 100
TypeError: 'tuple' object does not support item assignment
Accessing Values in Python Tuples
Tuples in Python provide two ways by which we can access the elements of a tuple.
Python Access Tuple using a Positive Index
Using square brackets we can get the values from tuples in Python.
Python `
tup = (10, 5, 20)
print("Value in tup[0] = ", tup[0]) print("Value in tup[1] = ", tup[1]) print("Value in tup[2] = ", tup[2])
`
Output
Value in tup[0] = 10 Value in tup[1] = 5 Value in tup[2] = 20
Access Tuple using Negative Index
In the above methods, we use the positive index to access the value in Python, and here we will use the negative index within [].
Python `
tup = (10, 5, 20)
print("Value in tup[-1] = ", tup[-1]) print("Value in tup[-2] = ", tup[-2]) print("Value in tup[-3] = ", tup[-3])
`
Output
Value in tup[-1] = 20 Value in tup[-2] = 5 Value in tup[-3] = 10
Below are the different operations related to tuples in Python:
**Traversing Items of Python Tuples
Like List Traversal, we can traverse through a tuple using for loop.
Python `
Define a tuple
tup = (1, 2, 3, 4, 5)
Traverse through each item in the tuple
for x in tup: print(x, end=" ")
`
**Concatenation of Python Tuples
To Concatenation of Python Tuples, we will use plus operators(+).
Python `
Code for concatenating 2 tuples
tup1 = (0, 1, 2, 3) tup2 = ('python', 'geek')
Concatenating above two
print(tup1 + tup2)
`
Output
(0, 1, 2, 3, 'python', 'geek')
**Nesting of Python Tuples
A nested tuple in Python means a tuple inside another tuple.
Python `
Code for creating nested tuples
tup1 = (0, 1, 2, 3) tup2 = ('python', 'geek')
tup3 = (tup1, tup2) print(tup3)
`
Output
((0, 1, 2, 3), ('python', 'geek'))
**Repetition Python Tuples
We can create a tuple of multiple same elements from a single element in that tuple.
Python `
Code to create a tuple with repetition
tup = ('python',)*3 print(tup)
`
Output
('python', 'python', 'python')
Try the above without a comma and check. You will get tuple3 as a string 'pythonpythonpython'.
**Slicing Tuples in Python
Slicing a Python tuple means dividing a tuple into small tuples using the indexing method. In this example, we slice the tuple from index 1 to the last element. In the second print statement, we printed the tuple using reverse indexing. And in the third print statement, we printed the elements from index 2 to 4.
Python `
code to test slicing
tup = (0 ,1, 2, 3)
print(tup[1:]) print(tup[::-1]) print(tup[2:4])
`
Output
(1, 2, 3) (3, 2, 1, 0) (2, 3)
**Note: In Python slicing, the end index provided is not included.
**Deleting a Tuple in Python
In this example, we are deleting a tuple using 'del' keyword. The output will be in the form of error because after deleting the tuple, it will give a NameError.
**Note: Remove individual tuple elements is not possible, but we can delete the whole Tuple using Del keyword.
Python `
Code for deleting a tuple
tup = ( 0, 1)
del tup print(tup)
`
**Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 5, in
print(t)
NameError: name 't' is not defined
**Finding the Length of a Python Tuple
To find the length of a tuple, we can use Python's len() function and pass the tuple as the parameter.
Python `
Code for printing the length of a tuple
tup = ('python', 'geek') print(len(tup))
`
Multiple Data Types With Tuple
Tuples in Python are heterogeneous in nature. This means tuples support elements with multiple datatypes.
Python `
tuple with different datatypes
tup = ("immutable", True, 23) print(tup)
`
Output
('immutable', True, 23)
**Converting a List to a Tuple
We can convert a list in Python to a tuple by using the tuple() constructor and passing the list as its parameters.
Python `
Code for converting a list and a string into a tuple
a = [0, 1, 2] tup = tuple(a)
print(tup)
`
**Output:
Tuples take a single parameter which may be a list, string, set, or even a dictionary(only keys are taken as elements), and converts them to a tuple.
**Tuples in a Loop
We can also create a tuple with a single element in it using loops.
Python `
python code for creating tuples in a loop
tup = ('gfg',)
Number of time loop runs
n = 5 for i in range(int(n)): tup = (tup,) print(tup)
`
Output
(('gfg',),) ((('gfg',),),) (((('gfg',),),),) ((((('gfg',),),),),) (((((('gfg',),),),),),)
Different Ways of Creating a Tuple
- Using round brackets
- Without Brackets
- Tuple Constructor
- Empty Tuple
- Single Element Tuple
- Using Tuple Packing
**Using Round Brackets
Python `
tup = ("gfg", "Python") print(tup)
`
**Using Comma Separated
Python `
Creating a tuple without brackets
tup = 4, 5, 6 print(tup)
`
**Using Tuple Constructor
Python `
Creating a tuple using the tuple() constructor
tup = tuple([7, 8, 9]) print(tup)
`
**Creating an Empty Tuple
Python `
Creating an empty tuple
tup = () print(tup)
`
**Single Element Tuple
Python `
Creating a single-element tuple
tup = (10, ) # Comma is important here print(tup) # Output: (10,) print(type(tup))
What if we do not use comma
tup = (10) # This an integer (not a tuple)
print(tup)
print(type(tup))
`
Output
(10,) <class 'tuple'> 10 <class 'int'>
**Tuple Packing
Python `
Tuple packing
a, b, c = 11, 12, 13 tup = (a, b, c) print(tup)
`
Tuple Built-In Methods
Tuples support only a few methods due to their immutable nature. The two most commonly used methods are count() and index()
| **Built-in-Method | **Description |
|---|---|
| **index( ) | Find in the tuple and returns the index of the given value where it's available |
| **count( ) | Returns the frequency of occurrence of a specified value |
Tuple Built-In Functions
| Built-in Function | Description |
|---|---|
| all() | Returns true if all element are true or if tuple is empty |
| any() | return true if any element of the tuple is true. if tuple is empty, return false |
| len() | Returns length of the tuple or size of the tuple |
| enumerate() | Returns enumerate object of tuple |
| max() | return maximum element of given tuple |
| min() | return minimum element of given tuple |
| sum() | Sums up the numbers in the tuple |
| sorted() | input elements in the tuple and return a new sorted list |
| **tuple() | Convert an iterable to a tuple. |
Tuples VS Lists
| **Similarities | **Differences |
|---|---|
| Functions that can be used for both lists and tuples:len(), max(), min(), sum(), any(), all(), sorted() | Methods that cannot be used for tuples:append(), insert(), remove(), pop(), clear(), sort(), reverse() |
| Methods that can be used for both lists and tuples:count(), Index() | we generally use 'tuples' for heterogeneous (different) data types and 'lists' for homogeneous (similar) data types. |
| Tuples can be stored in lists. | Iterating through a 'tuple' is faster than in a 'list'. |
| Lists can be stored in tuples. | 'Lists' are mutable whereas 'tuples' are immutable. |
| Both 'tuples' and 'lists' can be nested. | Tuples that contain immutable elements can be used as a key for a dictionary. |