Tuples in Python with Examples - A Beginner Guide
Python Programming For Beginners Free Course
Tuples in Python with Examples: An Overview
If you are just getting started with a Python certification course, you've probably heard about tuples. In this Python Tutorial, we'll take a look at what makes tuples so special, tutorials on how to use them, as well as some clever ways in which you can use them in your programming projects. So if you're ready to get coding with Python's most infamous structure let us begin!
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.
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')
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:- Use the index in square brackets: By utilizing their index, you can access particular elements (starting from 0).
- Use a negative index: Access elements starting at the end (last element, -1, for example).
- Use slicing: Colon (:) can be used to access various elements.
- Use unpacking: Extract several elements into different variables.
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
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')
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')
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
- The process of using an index to retrieve a particular element from a sequence (list, string, tuple, or array) is known as indexing.
- Extracting a subsequence from a sequence is referred to as "slicing." Within square brackets, you give the beginning index and the ending index (inclusive).
- A rectangular array of data is called a matrix. Every element has a unique index for both rows and columns.
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. |
Different Operations Related to Tuples
- Concatenation: The joining of two or more lists to form a new list.
- Nesting: Nesting is the process of putting one list inside another.
- Repetition: Making many copies of a list is an example of repetition.
- Slicing: Slicing is the process of extracting a part of a list.
- Deleting: The act of removing an item from a list.
- Determining the length: Counting the number of elements in a list.
- Multiple Data Types Using Tuples: Storing different data types in a tuple.
- Converting a list to a tuple: Making a tuple from a list.
- Tuples in a Loop: Iterating over the items in a tuple.
Summary