Python Tuples Tutorial

Sovary June 28, 2022 474
4 minutes read

Today you will learn about tuple in Python with simple example. I will explain what are tuples? how to use them? show use case in real world example with built-in methods which come with tuple.

python_tuple_example_usage_explain

Tuple

"tuple" is similar to list that can store multiple items in a single variable. The tuple can not change the item once it is assigned (immutable) where can change the item. We write tuple by placing all item in a pair of parentheses () separated by comma.

Tuple items are ordered, unchangeable, and allow duplicate values. Tuple allow to store item in different type (string, float, integer..etc).

Create Tuple

To create tuple with items we write each item in parentheses and separated by comma. For create one item in tuple you have to add a comma to mark as it is a tuple.

Example #1 - Create Tuple 

# Empty tuple
fruit = ()
print(fruit)

# One tuple with a comma to mark it is tuple
fruit = ("banana",)
print(fruit)

# Tuple having string
fruit = ("banana","mango","apple")
print(fruit)

# Tuple different item without parentheses
elements = 1,"item", True, 3.14

print(elements)

Access Tuple Elements

The way accessing item in tuple is the same way in list. We use index in square bracket to access the item. Tuple is zero base-index which is always start with 0 (Zero) located where the first element place and also support negative index. Let's see example below

fruits Orange Logan Grape Banana
Index 0 1 2 3
Negative Index -4 -3 -2 -1

Example #1 - Access Tuple Item

# Tuple having string
fruit = ("Orange","Logan","Grape","Banana")
print(fruit[0])
# Get first item the same
print(fruit[-4])

Output #1

Orange
Orange

Example #2 - Access Tuple Item in Range (Slice)

We can specifiy range of indexes where to start and end will return new tuple with range items. Example below will search item from 1st  index till 2nd index.

# Tuple having string
fruit = ("Orange","Logan","Grape","Banana","Kiwi","Lemon")
print(fruit[1:3])

Output #2

('Logan', 'Grape')

Example #3 - Access Tuple Item in Range without Start or End index.

# Tuple having string
fruit = ("Orange","Logan","Grape","Banana","Kiwi","Lemon")
print(fruit[4:])
print(fruit[:3])

Output #3

('Kiwi', 'Lemon')
('Orange', 'Logan', 'Grape')

Update Tuple

We already metion that tuple can not change (immutable), so how can we update tuple items? there is an option is to create new list and after modify we convert to tuple back.

Example #1 - Using List Modified Tuple

fruit = ("Orange","Logan","Grape")

# Convert to List
newFruit = list(fruit)

# Modified item in list
newFruit[0] = "Cherry"
fruit = tuple(newFruit)

print(fruit)

Output #1

('Cherry', 'Logan', 'Grape', 'Banana', 'Kiwi', 'Lemon')

Example #2 - Join Tuple

fruit = ("Orange","Logan","Grape")

# Append to tuple
fruit = fruit + ("Lemon",)
print(fruit)

Output #2

('Orange', 'Logan', 'Grape', 'Lemon')

Remove Item Tuple

Tuple is unchangable (immutable) but we can use the same method as above which is convert to list and remove then convert back to tuple.

Example #1 - Remove Item Tuple

fruit = ("Orange","Logan","Grape")

newFruit = list(fruit)
# Remove in List with specific item
newFruit.remove("Logan")
fruit = tuple(newFruit)
print(fruit)

Output #1

('Orange', 'Grape')

Example #2 - Remove Tuple

We can remove entire tuple by using del keyword.

fruit = ("Orange","Logan","Grape")
del fruit

# Error produce
print(fruit)

Output #2

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    print(fruit)
NameError: name 'fruit' is not defined

Unpack Tuple

The way we create tuple above is called packing tuple. We also unpacking tuple which is extract each item to another variable.

Example #1 - Unpack Tuple to Variable

# Packing Tuple
fruit = ("Orange","Logan","Grape")

# Unpacking Tuple
(item1, item2, item3) = fruit

print(item1)
print(item2)
print(item3)

Output #1

Orange
Logan
Grape
NOTE: Unpack tuple possible when there are number of variables match the items in tuple. Unless you must use asterisk (*) prefix to hold remain items in tuple.

Example #2 - Unpack Tuple with Less Variables

# Packing Tuple
fruit = ("Orange","Logan","Grape","Cherry","Mango")

# Unpacking Tuple, item2 hold remain items
(item1, *item2, item3) = fruit

print(item1)
print(item2)
print(item3)

Output #2

Orange
['Logan', 'Grape', 'Cherry']
Mango

Tuple Methods

Method Description
count() Return count number of times whihc appear in tuple
index() Return index of searching item appear at first place

Example #1 - Using index()

fruit = ("Orange","Logan","Grape","Cherry","Mango")

index = fruit.index("Logan")
print(index)

Output #1

1

Example #2 - Using count()

fruit = ("Orange","Logan","Grape","Cherry","Mango","Logan")

found = fruit.count("Logan")
print(found)

Output #2

2

Loop Tuple

We can iterate each item in tuple, I have wrote an article about for loop and while loop please check for more detail.

Example #1 - Using For in Item

fruit = ("Orange","Logan","Grape","Cherry","Mango","Logan")

for item in fruit:
  print(item)

Example #2 - Using Loop For Index

fruit = ("Orange","Logan","Grape","Cherry","Mango","Logan")

for index in range(len(fruit)):
  print(fruit[index])

Example #3 - Using While Loop

fruit = ("Orange","Logan","Grape","Cherry","Mango","Logan")
index = 0
while index < len(fruit):
  print(fruit[index])
  index=index+1

Output #1 #2 #3 The same result

Orange
Logan
Grape
Cherry
Mango
Logan

Hope you find something to learn, Have a nice day!

 

Python 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him