A tuple is very much like a list, except for the fact that its elements are fixed; that is, once a tuple is created, you cannot add new elements, delete elements, replace elements, or reorder the elements in the tuple.
Creating a tuple
- empty tuple
tuple = ( )
- tuple with integer elements
tuple = (2, 3, 4 )
- tuple with string elements
tuple = ("hello", "all")
- nested tuple
tuple = (("hello", "all"), (2, 4, 5))
- tuple with mixed type elements
tuple = ("hi", 3, 4.0)
- tuple with a single element
tuple = (1, )
When a tuple has only one element, we must put a comma after the element, otherwise python will not treat it as a tuple.
CODE
Built-in tuple functions
- len() : To find the length of a tuple.
- max() : To find the largest element in a tuple.
- min() : To find the smallest element in a tuple.
- sum() : To find the sum of all elements in a tuple.
CODE
Tuple operators
- Index operator : To access an element in a tuple from its index. Python also allows the use of negative numbers as indexes to reference positions relative to the end of a tuple.
CODE
- Slicing operator : The slicing operator returns a slice of the tuple using the syntax tuple[start : end]. The slice is a sub-tuple from start index to index end – 1.
CODE
- Concatenation operator (+) : To concatenate or join two tuples.
CODE
- Repetition operator (*) : To replicate elements in a tuple or create a duplicate of all tuple elements.
CODE
- in and not in operator : To check for the presence of an element in a tuple.
CODE
- Operators for comparing tuples : (>, >=, <, <=, ==, and !=)
CODE
Lists vs Tuples
- Lists are mutable whereas tuples are immutable.
- Lists consume more memory space as compared to tuples.
- Lists have comparatively greater number of built-in methods and functions.
- Lists have variable length whereas tuples have fixed length.
- Operations on tuples have smaller size than that of lists, making it a bit faster.
Happy coding !!