python
  1. python-tuples

Python Tuples

Tuples are ordered, immutable and indexed collection of elements. They are similar to lists but the difference is that tuples are immutable i.e. once created cannot be modified.

Syntax

#creating an empty tuple
tup = ()

#creating tuple with elements
tup = (elem1, elem2, elem3, ...)

#creating tuple with single element
tup = (elem1, )

#indexing 
tup[index]

#slicing 
tup[start:stop:step]

#joining tuples
tup1 + tup2

#repeating tuples
tup * n

#finding length of tuple
len(tup)

Example

#creating tuple with elements
tup = ('apple', 'mango', 'banana')
print(tup)          # Output: ('apple', 'mango', 'banana')

#repeating tuples
tup1 = (1, 2, 3)
tup2 = tup1 * 3
print(tup2)         # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)

#indexing 
print(tup[1])       # Output: mango
print(tup[-1])      # Output: banana

#slicing 
print(tup[1:3])     # Output: ('mango', 'banana')

#joining tuples
tup1 = (1, 2)
tup2 = ('red', 'blue')
tup3 = tup1 + tup2
print(tup3)         # Output: (1, 2, 'red', 'blue')

#finding length of tuple
tup = ('apple', 'mango', 'banana')
print(len(tup))     # Output: 3

Explanation

  • Creating an empty tuple is straightforward. You simply use empty parentheses i.e. ‘()’.
  • Tuple can be created with elements enclosed in round brackets separated by a comma.
  • To create a tuple with a single element, include a trailing comma after the element.
  • Tuple indexing is similar to list indexing.
  • Tuple slicing is similar to list slicing.
  • Like lists, tuples can be concatenated and repeated.
  • The len() function returns the number of elements in the tuple.

Use

Tuples are used when we want to store a collection of elements and we do not want to change them later.

Important Points

  • Tuples are immutable i.e., once created they cannot be modified.
  • Tuples can be used as keys in a dictionary, while lists cannot.
  • Tuple elements cannot be deleted individually from the tuple.
  • It is a good practice to use tuples to group related values together.

Summary

  • Tuples are ordered, immutable and indexed collection of elements.
  • They are created by enclosing elements in round brackets separated by a comma.
  • Tuples can be joined, repeated and indexed.
  • Tuples have fixed length and once created cannot be modified.
Published on: