Tuple in Python is one of the sequence data type that can store a group of elements. Tuple is similar to Python list with one notable difference that the Tuple is immutable where as list is mutable.
Once a tuple is created you can’t modify its elements. So performing operations like insert(),remove(), pop(), clear() are not possible on tuples.
Some of the important points about Python Tuple are-
- A tuple can store elements of different types.
- Tuple maintains the insertion order. Elements are inserted sequentially and you can iterate them in the same order.
- Tuple is immutable. So, it is not possible to change content of a tuple.
- Tuples can be indexed (both positive and negative) and sliced.
In this article we’ll see some of the features of the Python tuples with examples, methods in Tuple and functions that can be used with tuple.
Creating a tuple
1. In Python tuple is created by grouping elements with in parenthesis (), where the elements are separated by comma. It is the preferred way and also necessary in some scenarios.
# empty tuple t = () print(t) # tuple with items having different types t = (12, 54, 'hello!') print(t) # tuple containing lists t = ([1, 2, 3], [4, 5, 6]) print(t)
Output
() (12, 54, 'hello!') ([1, 2, 3], [4, 5, 6])
Here note that though Tuple itself is immutable but it can contain mutable objects like list.
2. When a tuple with one item is constructed value should be followed by a comma (it is not sufficient to enclose a single value in parentheses).
t = (1) print(type(t)) t = (1,) print(type(t))
Output
<class 'int'> <class 'tuple'>
As you can see, in first assignment type of t is integer not tuple. In the second assignment when value is followed by comma, the type of t is tuple.
3. You can also create a tuple using tuple() type constructor. An iterable can be passed as an argument to create a tuple, if no argument is passed then an empty tuple is created.
t = tuple() print(t) print(type(t))
Output
() <class 'tuple'>
When argument is passed-
#Tuple as argument t = tuple((1,2,3)) print(t) print(type(t)) #List as argument t = tuple([1, "Test", 4.56]) print(t) print(type(t))
Output
(1, 2, 3) <class 'tuple'> (1, 'Test', 4.56) <class 'tuple'>
Tuple packing and unpacking
Tuple can also be created without using parenthesis, it is known as tuple packing.
t = 3, 4, 'Hello' print(t) print(type(t))
Output
(3, 4, 'Hello') <class 'tuple'>
You can also do tuple unpacking by assigning tuple items to variables, unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence.
#packing t = 3, 4, 'Hello' print(t) print(type(t)) #unpacking x, y, z = t print('x',x) print('y',y) print('z',z)
Output
(3, 4, 'Hello') <class 'tuple'> x 3 y 4 z Hello
Accessing tuple elements using index
Tuple in python uses index starting from 0 to (tuple_length-1), it also uses negative indexing which starts at -1 from the end (right most element) and goes till tuple_length.
Here is an example showing tuple indexing for the stored elements.
To access an element of the tuple you can pass the corresponding index in the square brackets. For example to access the 5th element in a tuple you will pass tuple[4], as index starts from 0.
t = (2, 3, 6, 7, 9) # 1st element print(t[0]) #last element print(t[4]) #last element print(t[-1]) #first element print(t[-5])
Output
2 9 9 2
Trying to pass index beyond the index range of the tuple results in ‘index error’. For example here is a tuple having 5 elements so index range for the tuple is 0..4, trying to access index 5 results in an error.
t = (2, 3, 6, 7, 9) print(t[6])
Output
IndexError: tuple index out of range
Slicing a tuple
Just like string slicing you can do tuple slicing too which returns a new tuple.
Format of tuple slicing is as follows-
Tupleobject[start_position: end_position: increment_step]
- start_position is the index from which the slicing starts, start_position is included.
- end_position is the index at which the tuple slicing ends, end_position is excluded.
- increment_step indicates the step size. For example if step is given as 2 then every alternate element from start_position is accessed.
All of these parameters are optional, if start_position is not specified then the slicing starts from index 0. If end_position is not specified then the slicing ends at list_length – 1 (last index). If increment_step is not specified then increment step is 1 by default.
t = [2, 4, 6, 8, 10] print(t[1:len(t):2]) #[4, 8] t = [2, 4, 6, 8, 10] print(t[::])#[2, 4, 6, 8, 10] print(t[-3:])#[6, 8, 10]
Methods in tuple
Tuples provide the following two methods-
- count(x)- Returns the number of items x
- index(x)- Returns the index of the first item that is equal to x
Functions that can be used with tuple
- len- The len() function returns the number of items of a sequence
- min- The min() function returns the minimum element in a sequence
- max- The max() function returns the maximum element in a sequence
- sorted- Return a new sorted list from the items in iterable.
Operators used with tuples
Tuples can be used with the following operators which result in a creation of new tuple.
- + (concatenation)
- * (replication)
- [] (slice)
Iterating a tuple
You can iterate all elements of a tuple using for or while loop.
1. Using for loop
t = [3, 1, 9, 2, 5] for i in t: print(i)
Output
3 1 9 2 5
2. Using while loop
t = [3, 1, 9, 2, 5] i = 0; while i < len(t): print(t[i]) i += 1
Output
3 1 9 2 5
del keyword with tuple
Since tuple is immutable so elements can’t be modified or removed from a tuple but tuple itself can be deleted entirely using del keyword along with tuple instance.
t = [3, 1, 9, 2, 5] print(t) del t print(t)
Output
[3, 1, 9, 2, 5] print(t) NameError: name 't' is not defined
Second print(t) statement results in an error as tuple t is already deleted.
That's all for this topic Tuple in Python With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment