Let us know more about Tuples in Python. Think of types as a secure container for your data, once stored, it stays unchanged. Unlike lists, tuples are immutable, making them perfect for fixed data structures. Though simple, they pack powerful operations and unique use cases. In this article, we will go through what makes tuples special and how to use them effectively in Python.
What are Tuples?
Tuples are a type of data structure in Python that are used to store a collection of items. Tuples are a type of data structure that allows you to store multiple values in a single variable. Tuples are similar to lists in Python but are not same totally. Tuples can store elements of different data types like strings, integers, float, and others. Tuples are immutable, which means they cannot be modified once they are created.
Tuples are commonly used when you want to group related pieces of information together. They ensure that the group of information stays unchanged throughout your program.
Tuples are faster than Lists in Python in execution and are used based on its requirements where we need immutable and fast execution. The immutability of tuple ensures data integrity.
Creating a Tuple
Creating tuples in Python is an easy task that can be done using two different approaches. First, You can create a tuple by placing values inside parenthesis (), separated by commas. Secondly, you can use tuple() function to change a list or collection into a tuple.
Tuple Creation |
---|
#Creating a tuple
fruits = (“apple”, “banana”, 5, “cherry”) #Tuples with mixed data types person = (“John”, 25, True, 5.7) #When the tuple only contain one element, we need to add comma at the end single_element_tuple = (“Hello”, ) Not_a_tuple = (“Hello”) #this is just a string #conversion of a list into tuple my_List = [1, 2, 3, 4] my_tuple = tuple(my_List) |
Accessing Tuple Elements
Accessing elements of a tuple is similar to lists in Python. We can access the elements of the tuple based on their index values. You can access elements in a tuple using indexing, just like lists. We just need to remember that indexing in Pythin starts from 0.
Accessing Elements of Tuple |
---|
colors = (“red”, “green”, “blue”)
print(colors[0) print(colors[2]) |
Output:
red blue |
#We can also use negative indexing to access elements
colors = (“red”, “green”, “blue”) print(colors[-1]) |
Output:
blue |
Slicing Tuples in Python
We can extract a part of a tuple using these slicing. Slicing provide us a portion of the tuple in a tuple format. For slicing, we need to give the starting index and the ending index separated by a colon. Slicing is majorly used to access portion of a tuple in big projects without creating a new separate tuple for it.
Slicing Tuples |
---|
number = (10, 20, 30, 40, 50)
print(number[1:4]) print(number[ :3]) print(number[2: ]) |
Output:
(20, 30, 40) (10, 20, 30) (30, 40, 50) |
Tuple Immutability
Tuples in Python are immutable, as we have learned above. Now, what is immutable data structure? Immutable here means that once a tuple is created in Python, its contents cannot be altered in any way. You cannot change, add, or remove elements from the tuples after they have been defined.
Python will raise an error if we try to change, add or remove any content from the tuple. Let us see once through code:
Tuple Immutability |
---|
my_Tuple = (1, 2, 3, 4)
my_Tuple[1] = 5 |
Output:
TypeError: ‘tuple’ object does not support item assignment However, if a tuple contains any mutable object like a list, we can still modify that object. For instance, |
Tuple containing Mutable Elements |
---|
nested_Tuple = (1, 2, [3, 4])
nested_Tuple[2][0] = 99 print(nested_Tuple) |
Output:
(1, 2, [99, 4]) |
Operations Of Tuple
Even though tuples are immutable, but you can still perform several operations on them. Some of the most common operations, including concatenation, repetation, and more.
Concatenation
You can merge two tuples in Python using the concatenation (+) operator. This operator returns a tuple in python with elements of both tuples.
Concatenation of Tuples |
---|
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6) result = tuple1 + tuple2 print(result) |
Output:
(1, 2, 3, 4, 5, 6) |
Repetition
You can repeat a tuple using the repetition (*) operator. This operator returns a tuple with elements of tuples for times mentioned.
Repetition of Tuples In Python |
---|
repeat_Tuple = (“Hello”, ) * 3
print(repeat_Tuple) |
Output:
(“Hello”, “Hello”, “Hello”) |
Membership Test
This test checks whether the element exists in a tuples in Python using the ‘in’ keyword.
Membership Test |
---|
numbers = (10, 20, 30, 40)
print(20 in numbers) print(50 in numbers) |
Output:
True False |
Tuple Methods
Even though tuples in Python are immutable, Python provides a few built-in methods for working with them. Some of the built-in methods are mentioned below:
- count(value): Returns the number of times a value appears in the tuple
- index(value): Returns the first index where the value appears
Tuple Methods |
---|
my_Tuple = (1, 2, 3, 2, 4, 2)
print(my_Tuple.count(2)) print(my_Tuple.index(3))
|
Output:
3 2 |
Packing and Unpacking Tuples
Tuple Packing
You can store multiple values in a single variable, termed as the packing of a tuple.
Tuple Packing |
---|
packed_Tuple = “apple”, “banana”, “cherry”
print(packed_Tuple) |
Output:
(“apple”, “banana”, “cherry”) |
Tuple Unpacking
Now, tuples in python unpacking can extract values from a tuple into separate variables
Tuple Unpacking |
---|
fruits = (“apple”, “banana”, “cherry”)
a, b, c = fruits print(a) print(b) print(c) |
Output:
apple banana cherry |
Now, if you wish to store values in a list, use *
numbers = (1, 2, 3, 4, 5) first, *middle, last = numbers print(first) print(middle) print(last) |
Output:
1 [2, 3, 4] 5 |
Converting Between Lists and Tuples
We can convert between lists and tuples pretty easily in Python. You are given the tuple() and list() methods respectively, to convert into a tuple and a list.
Converting Between Lists and Tuples |
---|
#List to tuple
my_List = [1, 2, 3] my_Tuple = tuple(my_List) print(my_Tuple) #Tuple to List new_List = list(my_Tuple) print(new_List) |
Output:
(1, 2, 3) [1, 2, 3] |
When To Use Tuples In Python?
Tuples can be used in different scenarios. Some of the major scenarios where using tuple is considered are:
- Ensuring data remains unchanged: As we know now that tuples are immutable, for instance Days of the week
- Using Tuples as Dictionary keys: Since tuples are immutable, they can be used as dictionary keys
- Returning Multiple values from functions: Functions can return mutiple values as a tuple.
Learn Complete Python Programming with PW Skills
Become a skilled Python developer with the knowledge of Data Structures in Python. Get enrolled in PW Skills Decode DSA With Python Course and get in-depth tutorials, practice exercises, real world projects and more with this self paced learning program.
You will learn through industry oriented curriculum and prepare for competitive programming with this course. Get a industry recognised certification from PW Skills after completing the course.
Tuples in Python FAQs
Q1. What are tuples?
Ans. Tuples are a type of data structure in Python that are used to store a collection of items.
Q2. What is a tuple in Java?
Ans: Tuples allow you to express an array with a fixed number of elements of different types, resulting in a data structure with multiple different types. They are particularly useful when dealing with scenarios such as representing coordinates, storing key-value pairs, or returning multiple values from a function.
Q3. Why are tuples ordered in Python?
Ans. Tuples can store elements of different data types like strings, integers, float, and others. Tuples are immutable, which means they cannot be modified once they are created.