Tuples in python

Tuples in python

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

image.png

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

    image.png

    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

    image.png
  • 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

    image.png
  • Concatenation operator (+) : To concatenate or join two tuples.

    CODE

    image.png
  • Repetition operator (*) : To replicate elements in a tuple or create a duplicate of all tuple elements.

    CODE

    image.png
  • in and not in operator : To check for the presence of an element in a tuple.

    CODE

    image.png
  • Operators for comparing tuples : (>, >=, <, <=, ==, and !=)

    CODE

    image.png

    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 !!