Python tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parenthesis. Tuples can be thought of as read-only lists.
Example 1: use of Tuples
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') print (tuple) # Prints complete tuple print (tuple[0]) # Prints first element of the tuple print (tuple[1:3]) # Prints elements starting from 2nd till 3rd print (tuple[2:]) # Prints elements starting from 3rd element print (tinytuple * 2) # Prints tuple two times print (tuple + tinytuple) # Prints concatenated tuple
('abcd', 786, 2.23, 'john', 70.200000000000003) abcd (786, 2.23) (2.23, 'john', 70.200000000000003) (123, 'john', 123, 'john') ('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')
The main difference between lists and tuples are −
S.No | List | Tuple |
---|---|---|
Lists are enclosed in brackets [ ] | Tuples are enclosed in parentheses ( ) | |
List element value can be changed | Tuple element value cannot be updated | |
List size can be grow or shrink | Tuples size cannot be grow or shrink | |
Lists are shower than tuples. | Tuples are faster than list. |
Example 2: Difference between list and tuple
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tuple[2] = 1000 # Invalid syntax with tuple list[2] = 1000 # Valid syntax with list
Python tuple is an immutable object. Hence any operation that tries to modify it (like append, remove) is not allowed.
However, you can perform modify a tuple with the help of list. First, convert tuple to list, append/remove item to list object, then convert the list back to tuple.
Example 3: Method 1 - Convert tuple into list using list constructor
t = ( 'java', 5 , 'python', 'django' ) l=list(t) l.append('HTML') t=tuple(l) print(t)
Example 4: Method 2 - Convert tuple into list using unpacking
t = ( 'java', 5 , 'python', 'django' ) l=[*t] l.append('HTML') t=tuple(l) print(t)
Example 5: Method 3 - Convert tuple into list using unpacking
t = ( 'java', 5 , 'python', 'django' ) l=[] for x in t: l.append(x) l.append('HTML') t=tuple(l) print(t)