Tuple in Python are ordered collection of data items. They store multiple items in a single variable. Tuple items are separated by commas and enclosed within round brackets (). Tuples are unchangeable meaning we can not alter them after creation.
In Python, tuples are versatile data structures similar to lists, but with one key difference: they are immutable, meaning their elements cannot be changed after creation. In this guide, we’ll dive into the meaning of tuples, explore examples to illustrate their usage, address common questions, and conclude with insights on their significance.
What is Tuple in Python?
Tuples are ordered collections of elements, just like lists, but they are immutable. Once created, the elements of a tuple cannot be modified, added, or removed.
Example:
Think of a tuple as a fixed set of items that you can’t change. For instance, coordinates (x, y) in a Cartesian plane can be represented as a tuple.
coordinates = (3, 5)
PythonExample 1:
tuple1 = (1,2,2,3,5,4,6)
tuple2 = ("Red", "Green", "Blue")
print(tuple1)
print(tuple2)
PythonOutput:
(1, 2, 2, 3, 5, 4, 6)
('Red', 'Green', 'Blue')
PythonExample 2:
details = ("Abhijeet", 18, "FYBScIT", 9.8)
print(details)
PythonOutput:
('Abhijeet', 18, 'FYBScIT', 9.8)
Tuple Index in Python
Each item/element in a tuple has its own unique index. This index can be used to access any particular item from the tuple. The first item has index [0], second item has index [1], third item has index [2] and so on.
Example:
country = ("Spain", "Italy", "India", "England", "Germany")
# [0] [1] [2] [3] [4]
PythonAccessing Tuple Items in Python
I. Positive Indexing
As we have seen that tuple items have index, as such we can access items using these indexes.
Example:
country = ("Spain", "Italy", "India", "England", "Germany")
# [0] [1] [2] [3] [4]
print(country[1])
print(country[3])
print(country[0])
PythonOutput:
Italy
England
Spain
PythonII. Negative Indexing
Similar to positive indexing, negative indexing is also used to access items, but from the end of the tuple. The last item has index [-1], second last item has index [-2], third last item has index [-3] and so on.
Example:
country = ("Spain", "Italy", "India", "England", "Germany")
# [0] [1] [2] [3] [4]
print(country[-1])
print(country[-3])
print(country[-4])
PythonOutput:
Germany
India
Italy
PythonIII. Check for item
We can check if a given item is present in the tuple. This is done using the in keyword.
Example 1:
country = ("Spain", "Italy", "India", "England", "Germany")
if "Germany" in country:
print("Germany is present.")
else:
print("Germany is absent.")
PythonOutput:
Germany is present.
PythonExample 2:
country = ("Spain", "Italy", "India", "England", "Germany")
if "Russia" in country:
print("Russia is present.")
else:
print("Russia is absent.")
PythonOutput:
Russia is absent.
PythonIV. Range of Index
You can print a range of tuple items by specifying where do you want to start, where do you want to end and if you want to skip elements in between the range.
Syntax:
Tuple[start : end : jumpIndex]
Note: jump Index is optional. We will see this in given examples.
Example: printing elements within a particular range:
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[3:7]) #using positive indexes
print(animals[-7:-2]) #using negative indexes
PythonOutput:
('mouse', 'pig', 'horse', 'donkey')
('bat', 'mouse', 'pig', 'horse', 'donkey')
PythonHere, we provide index of the element from where we want to start and the index of the element till which we want to print the values.
Note: The element of the end index provided will not be included.
Example: printing all element from a given index till the end
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[4:]) #using positive indexes
print(animals[-4:]) #using negative indexes
PythonOutput:
('pig', 'horse', 'donkey', 'goat', 'cow')
('horse', 'donkey', 'goat', 'cow')
PythonWhen no end index is provided, the interpreter prints all the values till the end.
Example: printing all elements from start to a given index
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[:6]) #using positive indexes
print(animals[:-3]) #using negative indexes
PythonOutput:
('cat', 'dog', 'bat', 'mouse', 'pig', 'horse')
('cat', 'dog', 'bat', 'mouse', 'pig', 'horse')
PythonWhen no start index is provided, the interpreter prints all the values from start up to the end index provided.
Example: print alternate values
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[::2]) #using positive indexes
print(animals[-8:-1:2]) #using negative indexes
PythonOutput:
('cat', 'bat', 'pig', 'donkey', 'cow')
('dog', 'mouse', 'horse', 'goat')
PythonHere, we have not provided start and index, which means all the values will be considered. But as we have provided a jump index of 2 only alternate values will be printed.
Example: printing every 3rd consecutive withing given range
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[1:8:3])
PythonOutput:
('dog', 'pig', 'goat')
PythonHere, jump index is 3. Hence it prints every 3rd element within given index.
Manipulating Tuples in Python
Tuples are immutable, hence if you want to add, remove or change tuple items, then first you must convert the tuple to a list. Then perform operation on that list and convert it back to tuple.
Example:
countries = ("Spain", "Italy", "India", "England", "Germany")
temp = list(countries)
temp.append("Russia") #add item
temp.pop(3) #remove item
temp[2] = "Finland" #change item
countries = tuple(temp)
print(countries)
PythonOutput:
('Spain', 'Italy', 'Finland', 'Germany', 'Russia')
PythonThus, we convert the tuple to a list, manipulate items of the list using list methods, then convert list back to a tuple.
However, we can directly concatenate two tuples instead of converting them to list and back.
Example:
countries = ("Pakistan", "Afghanistan", "Bangladesh", "ShriLanka")
countries2 = ("Vietnam", "India", "China")
southEastAsia = countries + countries2
print(southEastAsia)
PythonOutput:
('Pakistan', 'Afghanistan', 'Bangladesh', 'ShriLanka', 'Vietnam', 'India', 'China')
Unpack Tuples in Python
Unpacking is the process of assigning the tuple items as values to variables.
Example:
info = ("Marcus", 20, "MIT")
(name, age, university) = info
print("Name:", name)
print("Age:",age)
print("Studies at:",university)
PythonOutput:
Name: Marcus
Age: 20
Studies at: MIT
PythonHere, the number of list items is equal to the number of variables.
But what if we have more number of items then the variables?
You can add an * to one of the variables and depending upon the position of variable and number of items, python matches variables to values and assigns it to the variables.
Example 1:
fauna = ("cat", "dog", "horse", "pig", "parrot", "salmon")
(*animals, bird, fish) = fauna
print("Animals:", animals)
print("Bird:", bird)
print("Fish:", fish)
PythonOutput:
Animals: ['cat', 'dog', 'horse', 'pig']
Bird: parrot
Fish: salmon
PythonExample 2:
fauna = ("parrot", "cat", "dog", "horse", "pig", "salmon")
(bird, *animals, fish) = fauna
print("Animals:", animals)
print("Bird:", bird)
print("Fish:", fish)
PythonOutput:
Animals: ['cat', 'dog', 'horse', 'pig']
Bird: parrot
Fish: salmon
PythonExample 3:
fauna = ("parrot", "salmon", "cat", "dog", "horse", "pig")
(bird, fish, *animals) = fauna
print("Animals:", animals)
print("Bird:", bird)
print("Fish:", fish)
PythonOutput:
Animals: ['cat', 'dog', 'horse', 'pig'] Bird: parrot Fish: salmon
PythonConclusion
Tuple are valuable data structures in Python, offering immutability and fixedness compared to lists. They are ideal for representing unchangeable data sets and provide a level of safety and predictability in your programs. By understanding tuples and their characteristics, you expand your toolkit for managing data effectively in Python. Embrace tuples when you need stability and reliability in your code, and unlock their potential for enhancing the robustness of your Python applications.
Frequently Asked Questions
Ans: Yes, tuples can hold elements of different data types, just like lists.
Q2. When Should I Use Tuples Instead of Lists?
Ans: Use tuples when you have a fixed set of data that you don’t want to change, such as coordinates, configuration settings, or database records.
Q3. How Do I Convert a List to a Tuple?
Ans: You can convert a list to a tuple using the tuple() function.my_list = [1, 2, 3]
my_tuple = tuple(my_list)