22
DecTuples in Python with Examples - A Beginner Guide
Python Tuples
In this Python Tutorial, we'll look at what makes tuples so special and how to define them in Python. We'll also explore different tuple operations in Python with examples and some clever ways to use them in your programming projects. So, if you're ready to get coding with Python's most infamous structure, let's start together!
What are Tuples in Python?
- Tuples are ordered collections of elements, similar to Python lists, but they are immutable.
- This implies that once a tuple has been created, it cannot be altered.Parentheses() are used to define tuples, while commas are used to separate the elements.
- They help store data that should not be modified, such as constants or sets of related data.
- there are various concepts related to tables such as tuple datatypes, methods, and operations. Let's see one-by-one
1. Pythons Tuple's Data Type
>>> blue= (0, 0, 255)
After blue has been defined, there is no need to modify or add any further elements. Why? Your variable name will be misleading if you alter the value of even one component, as you will no longer have a pure blue color. Your color won't be an RGB color if you add a new component. Therefore, tuples are ideal for representing this kind of data.
2. Characteristics of Tuple
- Ordered: The elements are grouped sequentially based on the order in which they were inserted.
- Lightweight: In comparison to other sequences like lists, they need very little memory.
- Zero-based indexable: You can retrieve their elements using integer indices that begin at zero.
- Immutable: They are resistant to alterations or in-place mutations to the elements they contain. They don't encourage operations to expand or contract.
- Heterogeneous: They are capable of holding changeable objects as well as objects with a variety of data types and domains.
- Nestable: You can have tuples of tuples since they can hold other tuples.
- Iterable: You can work with each of their elements by performing operations on them using a loop or comprehension, as they allow for iteration.
- Sliceable: You can extract a number of elements from a tuple because they allow slicing operations.
- Combinable: They can be used to combine two or more tuples using concatenation operators to create a new tuple because they support concatenation operations.
- Hashable: When every tuple item in a dictionary is unchangeable, they can function as keys.
3. Tuple Objects
>>> record = ("Sourav", 25, "SEO Manager")
>>> record
('Sourav', 25, 'SEO Manager')
This tuple's elements are objects of various data types that each represent a record of information from a database table. Accessing the tuple object will reveal that the data pieces maintain their original sequence of insertion. Throughout the tuple's existence, this order doesn't change.Within a tuple, you can retrieve specific objects using their index or position. Each of these indices begins at zero:
>>> record[0]
'Sourav'
>>> record[1]
25
>>> record[2]
'SEO Manager'
Creating Tuples in Python
In Python, there are multiple methods for creating a tuple.
They are listed in the following order:
- Making use of round brackets
- With just one item
- Tuple Constructor
Read More - 50 Python Interview Questions
1. Making use of round brackets
Python uses round brackets () to define tuples. Commas are used to separate the elements inside the brackets.Example of Creating Tuple in Python using Round Brackets
scholarhat_articles = ("C", "C++", "Python", "Java")
print(scholarhat_articles)
Output
('C', 'C++', 'Python', 'Java')
2. With just one item
In Python, a comma must be added after the element to create a tuple with just that one element. It will be understood as a string type otherwise.
Example of Creating Tuple in Python using just one item
favorite_color = ("blue",)
print(f"My favorite color is: {favorite_color[0]}")
Output
My favorite color is: blue
Read More - Python Developer Salary in India
3. Tuple Constructor
You can construct tuple objects in Python from many data structures by using the tuple constructor. It is essentially an inbuilt function in Python that accepts an iterable as input and outputs a tuple with all its elements.Example of Creating Tuple in Python using Tuple Constructor
my_list = ["apple", "banana", "cherry"]
my_tuple = tuple(my_list)
print(f"List: {my_list}")
print(f"Tuple: {my_tuple}")
Output
List: ['apple', 'banana', 'cherry']
Tuple: ('apple', 'banana', 'cherry')
Tuple Operations
1. How to Access Tuple Elements in Python
In Python, tuples are immutable lists of elements enclosed in parentheses.Different techniques can be used to access individual items within a tuple:
Example of Accessing Tuple Elements in Python
fruits = ("apple", "banana", "cherry")
# Access the second element (banana)
second_fruit = fruits[1]
print(second_fruit) # Output: banana
# Access the last element (cherry)
last_fruit = fruits[-1]
print(last_fruit)
After defining a tuple of fruits, this code uses positive indexing to access the second element ("banana") and negative indexing to get the last element ("cherry").
Output
banana
cherry
2. Updating Tuples in Python
Example of Updating Tuples in Python
tup1 = (16, 44.26);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print (tup3)
This code creates a new tuple called tup3 by combining two defined tuples, tup1 and tup2. It shows that while merging tuples is okay, changing a tuple is restricted.
Output
(16, 44.26, 'abc', 'xyz')
3. Delete Tuple Elements in Python
Example of Deleting Tuple Elements in Python Editor
original_tuple = ("apple", "banana", "orange", "grapefruit")
deleted_tuple = original_tuple[1:]
print("Original tuple:", original_tuple)
print("Deleted tuple:", deleted_tuple)
Four fruits make up the "original_tuple" that this code defines. The first member ("apple") is then removed using slicing to generate a new tuple called "deleted_tuple" (original_tuple[1:]). Lastly, it prints the changed and original tuples.
Output
Original tuple: ('apple', 'banana', 'orange', 'grapefruit')
Deleted tuple: ('banana', 'orange', 'grapefruit')
Other basic tuple operations in Python
Python Expression | Results | Description |
len((1, 2, 3)) | 3 | Length |
(1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | Concatenation |
('Hi!',) * 4 | ('Hi!', 'Hi!', 'Hi!', 'Hi!') | Repetition |
3 in (1, 2, 3) | True | Membership |
for x in (1, 2, 3): print x, | 1 2 3 | Iteration |
Indexing, Slicing, and Matrixes in Python
Python Expression | Results | Description |
L[2] | 'SPAM!' | Offsets start at zero |
L[-2] | 'Spam' | Negative: count from the right |
L[1:] | ['Spam', 'SPAM!'] | Slicing fetches sections |
Tuple built-in functions in Python
Sr.No. | Function | Description |
1 | cmp(tuple1, tuple2) | Compares elements of both tuples. |
2 | len(tuple) | Gives the total length of the tuple. |
3 | max(tuple) | Returns item from the tuple with max value. |
4 | min(tuple) | Returns item from the tuple with min value. |
5 | tuple(seq) | Converts a list into a tuple. |
6 Usages of Tuples in Python
- Retrieving Multiple Items From a Tuple: Slicing
- Tuple Immutability
- Packing and Unpacking Tuples
- Returning Tuples From Functions
- Creating Copies of a Tuple
- Concatenating and Repeating Tuples
1. Retrieving Multiple Items
- Tuples can also be used to extract a section or slice of its content using the slicing operation, which has the same syntax as regular Python sequences
- This construct's [start:stop:step] component is referred to as the slicing operator. It is composed of three optional indices (start, stop, and step) and two square brackets. There is also an optional second colon. It is usually reserved for situations in which you require a step value other than 1.
- The slicing operator's indices are all optional.
Their default values and meanings are summarized as follows:
These indices can be combined in many ways to extract particular parts of a given tuple. Here are some examples of slicing :
1. Basic Slicing
# Define a tuple
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# Slice from index 2 to 5 (exclusive)
slice1 = my_tuple[2:6]
print(slice1) # Output: (3, 4, 5, 6)
Output
(3, 4, 5, 6)
2. Slicing with a Step
# Slice from index 1 to 8 with a step of 2
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
slice2 = my_tuple[1:9:2]
print(slice2) # Output: (2, 4, 6, 8)
Output
(2, 4, 6, 8)
3. Omitting Start or End
# Define a tuple
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# Slice from the beginning to index 4 (exclusive)
slice3 = my_tuple[:5]
print(slice3) # Output: (1, 2, 3, 4, 5)
# Slice from index 5 to the end
slice4 = my_tuple[5:]
print(slice4) # Output: (6, 7, 8, 9, 10)
Output
(1, 2, 3, 4, 5)
(6, 7, 8, 9, 10)
4. Negative Indexing
# Define a tuple
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# Slice using negative indices
slice5 = my_tuple[-5:-1]
print(slice5) # Output: (6, 7, 8, 9)
# Slice using negative step to reverse
slice6 = my_tuple[::-1]
print(slice6) # Output: (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
Output
(6, 7, 8, 9)
(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
5. Full Slice
# Define a tuple
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# Full slice to create a copy of the tuple
slice7 = my_tuple[:]
print(slice7) # Output: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Output
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
2. Tuple Immutability
my_tuple = (10, 20, 30)
try:
my_tuple[0] = 100 # Trying to change the first element
except TypeError as e:
print(e) # Output: 'tuple' object does not support item assignment
# However, you can create a new tuple
new_tuple = my_tuple[:2] + (100,)
print(new_tuple) # Output: (10, 20, 100)
Output
'tuple' object does not support item assignment
(10, 20, 100)
Key Points of Tuple Immutability:
- You cannot modify the elements of a tuple after its creation.
- Attempting to change an element of a tuple will result in a TypeError
- You cannot add new elements to a tuple or remove existing ones.
- Methods like append(), remove(), and pop() are not available for tuple
- While the tuple itself is immutable, if it contains mutable objects like lists, the contents of those objects can be modified.
- To "modify" a tuple, you have to create a new tuple by concatenating or slicing existing tuples.
3. Packing and Unpacking Tuples
1. Packing Tuples
# Packing values into a tuple
my_tuple = 1, 2, 3
print(my_tuple) # Output: (1, 2, 3)
# Packing with parentheses (optional but clearer)
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)
Output
(1, 2, 3)
(1, 2, 3)
In the example above, 1, 2, and 3 are packed into the tuple my_tuple.
2. Unpacking Tuples
# Unpacking a tuple
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
Output
1
2
3
The tuple my_tuple is unpacked into variables a, b, and c in the above example.
Using the * Operator for unpacking:The * operator can also be used to unpack tuples, allowing you to capture multiple items in a list.
my_tuple = (1, 2, 3, 4, 5)
# Unpacking with the * operator
a, *b, c = my_tuple
print(a) # Output: 1
print(b) # Output: [2, 3, 4]
print(c) # Output: 5
Output
1
[2, 3, 4]
5
In this case, the initial value is taken by a, the last value is taken by c, and the middle values are stored in a list called b.
Practical Use Cases
x, y = 10, 20
x, y = y, x # Swaps the values
print(x, y) # Output: 20 10
def get_point():
return 1, 2
x, y = get_point()
print(x, y) # Output: 1 2
These concepts make Python code more readable and efficient, especially when working with multiple values.
These concepts could improve the readability and effectiveness of Python code, particularly when handling many values.
4. Returning Tuples From Functions
Python practices frequently return tuples, especially when you wish the function to return numerous values. Tuples are a great option for returning a set of related data because they may hold several immutable elements.
Basic Example
def get_coordinates():
x = 10
y = 20
return x, y # Returns a tuple (10, 20)
coordinates = get_coordinates()
print(coordinates) # Output: (10, 20)
Unpacking Returned Tuples
def get_coordinates():
x = 10
y = 20
return x, y # Returns a tuple (10, 20)
x, y = get_coordinates()
print(x) # Output: 10
print(y) # Output: 20
Returning Multiple Values
Returning a tuple is handy when a function needs to return multiple values of different types:
def analyze_data(data):
mean = sum(data) / len(data)
minimum = min(data)
maximum = max(data)
return mean, minimum, maximum # Returns a tuple (mean, min, max)
data = [4, 8, 15, 16, 23, 42]
mean, minimum, maximum = analyze_data(data)
print("Mean:", mean) # Output: Mean: 18.0
print("Minimum:", minimum) # Output: Minimum: 4
print("Maximum:", maximum) # Output: Maximum: 42
def process_args(*args):
return args # Returns a tuple of all arguments
result = process_args(1, 2, 3, "Python", True)
print(result) # Output: (1, 2, 3, 'Python', True)
Realistic Use Cases
- Multiple Results: Functions that do calculations and provide a number of related results.
- Efficient Data managing: Combining several return values into a tuple to make managing them easier.
- Data Transformation: Data transformation refers to operations, including unit conversions and coordinate conversions, that require the return of altered data in pairs.
5. Creating Copies of a Tuple: Using the Copy Module
import copy
original_tuple = (1, 2, 3)
copied_tuple = copy.copy(original_tuple)
print(copied_tuple) # Output: (1, 2, 3)
Output
(1, 2, 3)
6. Concatenating and Repeating Tuples
1. Concatenating Tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple) # Output: (1, 2, 3, 4, 5, 6)
Output
(1, 2, 3, 4, 5, 6)
2. Repeating Tuples
The * operator repeats a tuple a given number of times, which is useful for repeating its elements.tuple1 = (1, 2, 3)
repeated_tuple = tuple1 * 3
print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Output
(1, 2, 3, 1, 2, 3, 1, 2, 3)