E-Books

Python Tuples

Tuples are used to store multiple items in a single variable. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.


  mytuple = ("apple", "banana", "cherry")
  print(mytuple)
            

🧠 Tuple type() in Python

From Python's perspective, tuples are defined as objects with the data type 'tuple'


  mytuple = ("apple", "banana", "cherry")
  print(type(mytuple))  
            

🔸 Tuple Items are Ordered

When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.


  tp = ("apple", "banana", "cherry")
  print(tp[0])  # first item
  print(tp[1])  # second item             
            

🔸 Tuples Allow Duplicates Items in Python

Since tuples are indexed, they allow duplicate values. That means the same value can appear multiple times within a tuple.


  fruits = ("apple", "banana", "apple", "cherry", "banana")
  print(fruits)              
            

🔸 Tuple Items – Data Types in Python

In Python, tuples can store items of any data type. A tuple can even contain mixed data types in the same collection.


  mixed = (1, "hello", 3.14, True)
  print(mixed)              
            

🔸 Tuples are immutable in Python

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.


  fruits = ("apple", "banana", "apple")
  fruits[2] = "Mango"  # TypeError: 'tuple' object does not support item assignment
  print(fruits)
            

🔸 Tuple Length in Python

The length of a tuple refers to the number of elements it contains. You can easily find the length of a tuple using the built-in len() function.


  fruits = ("apple", "banana", "cherry")
  print(len(fruits))
            

🔸 Create Tuple With One Item in Python

To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.


  #NOT a tuple
  thistuple = ("apple")
  print(type(thistuple)) # <class 'str'>

  thistuple = ("apple",) # <class 'tuple'>
  print(type(thistuple))            
            

🔸 The tuple() Constructor in Python

The tuple() constructor is a built-in Python function used to create a tuple. It can convert other iterable data types like lists, strings, or sets into a tuple.

1. Creating tuple from a String in Python


  result = tuple('Python')
  print(result)                           
            


2.Creating tuple from a List in Python


  result = tuple([1, 2, 3])
  print(result)              
            


3. Creating tuple from a Set in Python


  result = tuple({"apple", "banana", "cherry", "apple"})
  print(result)              
            


4. Creating tuple from a Dictionary in Python


  result = tuple({'Name': 'Raj', 'age': 25})
  print(result)              
            


5. Creating tuple from a Range in Python


  result = tuple(range(1,11))
  print(result)              
            


6. Creating an Empty Tuple in Python


  empty_tuple = tuple()
  print(empty_tuple)                           
            


7. Creating a Tuple Using a Comma in Python


  fruits = "apple", "banana", "cherry"
  print(fruits)                          
            

🔸 Accessing Tuple Items in Python

Tuples in Python are ordered collections, which means that their items can be accessed using positive indexing or negative indexing.


  colors = ("red", "green", "blue", "yellow", "purple")
  print(colors[1])    
  print(colors[-2])
  print(colors[0])
  print(colors[-1])
  print(colors[-0])
  print(colors[5]) # ❌ IndexError: tuple index out of range
            

✂️ Tuple Slicing in Python

Slicing is used to extract a portion (subtuple) of a tuple by specifying a range of indexes.

Argument Description Default Value
start The index where the slice starts (inclusive). 0 (if step is positive), -1 (if step is negative)
stop The index where the slice ends (exclusive). len(S) (if step is positive), -len(S) (if step is negative)
step The interval between indices in the slice. 1 (default)


  my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

  print(my_tuple[:])       
  print(my_tuple[2:])      
  print(my_tuple[:4])      
  print(my_tuple[1:4])     
  print(my_tuple[::2])     
  print(my_tuple[1:5:2])   
  print(my_tuple[2::2])    
  print(my_tuple[:4:2])    
  print(my_tuple[4:1:-1])  
  print(my_tuple[5:1:-2])  
  print(my_tuple[0:10:-2]) 
  print(my_tuple[5::-2])   
  print(my_tuple[:5:-2])   
  print(my_tuple[::-1])    
            

🔸 Traversing a Tuple in Python

Traversing means accessing each item in a tuple one by one. You can traverse a tuple using a loop, most commonly a for loop or while loop.


  fruits = ("apple", "banana", "cherry", "mango")

  # Using for Loop
  for fruit in fruits:
      print(fruit)


  # Using while Loop
  i = 0
  while i < len(fruits):
      print(fruits[i])
      i += 1
            

🔸 Joining Tuples in Python

In Python, you can join (combine) two or more tuples using the + operator. This operation creates a new tuple containing all elements from the original tuples.


  tuple1 = ("apple", "banana", "cherry")
  tuple2 = ("orange", "mango")
  
  result = tuple1 + tuple2
  print(result)              
            

🔸 Repeating Tuples in Python

You can repeat a tuple multiple times using the * operator. This creates a new tuple where the elements are repeated as specified number of times.


  fruits = ("apple", "banana")
  result = fruits * 3
  print(result)              
            

🔸 Comparing Tuples in Python

Tuples can be compared using comparison operators. Comparison is done element by element, from left to right.


  # Equality
  print((1, 2, 3) == (1, 2, 3))
  
  # Not Equal
  print((1, 2, 3) != (3, 2, 1))
  
  # Less than (element-wise comparison)
  print((1, 2, 30) < (1, 20, 4))
  
  # Greater than
  print((7, 3, 5) > (1, 20, 90))
  
  # Shorter list vs longer
  print((1, 2) < (1, 2, 0))
  
  # Comparing strings in list
  print(('apple') < ('banana'))
            

🔸 Deletion in Tuples in Python


  fruits = ("apple", "banana", "cherry", "orange") 

  del fruits[1] # ❌ TypeError: 'tuple' object doesn't support item deletion
  print(fruits)
              
  # Delete a range of items
  del fruits[1:3] # ❌ TypeError: 'tuple' object doesn't support item deletion
  print(fruits)
              
  # Delete entire tuple
  del fruits
  print(fruits) # ❌ NameError: name 'fruits' is not defined
            

🔸 Packing and Unpacking Tuples in Python

Tuple Packing

Tuple packing is the process of combining multiple values into a single tuple. You can create a tuple by simply comma-separating values.


  fruits = ("apple", "banana", "cherry")
  print(fruits)              
            


Tuple Unpacking

Tuple unpacking is the process of extracting individual elements from a tuple and assigning them to variables. The number of variables must match the number of elements in the tuple.


  a, b, c = fruits
  
  print(a)  # apple
  print(b)  # banana
  print(c)  # cherry                           
            


Unpacking with More Variables Using *

If you don't know how many elements a tuple has, you can use * to collect remaining items:


  fruits = ("apple", "banana", "cherry", "orange", "mango")
  a, *b, c = fruits
  
  print(a)  # apple
  print(b)  # ['banana', 'cherry', 'orange']
  print(c)  # mango                                        
            

🔸 Tuple Methods and Function in Python

Tuples have a few built-in methods abd function that allow you to perform specific operations.

Method Description Example
max() Returns the largest item in the tuple. max((3, 1, 4)) → 4
min() Returns the smallest item in the tuple. min((3, 1, 4)) → 1
sum() Returns the sum of all items in the tuple (only numeric items). sum((1, 2, 3)) → 6
sorted() Returns a new sorted list from the tuple. sorted((3, 1, 4)) → [1, 3, 4]
index() Returns the index of the first occurrence of an item. ("apple",).index("apple") → 0
count() Returns the number of times an item appears in the tuple. ("apple",).count("apple") → 1
cmp() Compares two tuples (Python 2 only, removed in Python 3). N/A in Python 3

🔸 max() Function in Python

The max() function returns the largest item in an iterable (e.g., list, tuple) or the largest of two or more arguments.


  numbers = (1, 5, 3, 9, 2)
  print(max(numbers))              
            

🔸 min() Function in Python

The min() function returns the smallest item in an iterable (e.g., list, tuple) or the smallest of two or more arguments.


  numbers = (1, 5, 3, 9, 2)
  print(min(numbers))              
            

🔸 sum() Function in Python

The sum() function returns the sum of all items in an iterable (e.g., list, tuple) or the sum of two or more arguments.


  numbers = (1, 2, 3, 4, 5)
  print(sum(numbers))              
            

🔸 sorted() Function in Python

The sorted() function returns a new sorted list from the elements of any iterable (like a tuple, list, or string).


  tp = (7, 2, 5, 1, 4)
  result = sorted(tp)
  print("Original Tuple:", tp)
  print("Sorted List:", result)              
            

🔸 Tuples index() Method in Python

The index() method returns the index of the first occurrence of a specified value in a tuple. If the value is not found, it raises a ValueError.


  fruits = ("apple", "banana", "cherry", "banana")
  position = fruits.index("banana")
  print("Index of 'banana':", position)              
            

🔸 Tuples count() Method in Python

The count() method returns the number of times a specified value appears in the tuple.


  nums = (1, 2, 3, 4, '2', 22, 222)
  print(nums.count(2))              
            

🔸 cmp() function in Python 2 (Deprecated in Python 3)

Comparison cmp(a, b) (a > b) - (a < b)
a < b -1 -1
a == b 0 0
a > b 1 1


  a = (1, 2, 3)
  b = (1, 2, 4)

  result = (a > b) - (a < b)
  print(result)
            

Previous Next