Python is a high-level, all-purpose programming language designed to be used in a range of applications, including data science, software and web development, and automation. To date, it has been used in the creation of virtually everything — from the recommendation algorithm on Netflix to the self-driving cars’ controls software.
The popularity of Python is mainly driven by the simplicity of its syntax, which mimics natural English. As a result, it is easy to read and understand. Moreover, the language is very user-friendly for beginners, making it popular among beginning programmers. And since it is open source, it can be used and distributed for free, even for commercial purposes.
Tuple in Python is a collection of multiple items stored in an organized and immutable way. It’s one of the four built-in data types in Python programming. A tuple is similar to a list in terms of nested objects, repetition, and indexing. However, unlike lists, you cannot change the elements of a tuple once they have been assigned to it. Tuples are written using round brackets and can include any data type, including boolean, numeric, and dictionary.
In today's article, you'll discover all there is to know about using and creating tuples in Python.
Photo by Clément Hélardot on Unsplash
Python allows for the creation of tuples by enclosing all comma-separated items within parenthesis ().
First_tuple = (3, 6, 9, 12)
Second_tuple = ("Good", "Afternoon")
Third_tuple = (1.3, 2.5, 4.6, 3.4)
Tuple elements are the elements in parentheses. These can be of different types, such as float, double, string, or char, and can be put into the tuple during the tuple creation. The elements of a tuple are:
Tuples can have different types of data in a single parenthesis. Here are some examples of how to create and use tuples in Python:
An empty tuple has no value. You can create one by using empty parentheses.
first_tuple = ()
Output ()
If you want to create a single-value tuple, a comma must follow the single element.
first_tuple = ("pear",)
Output: (pear)
A mixed tuple can contain multiple comma-separated values. To create this tuple, you must separate each element within the brackets with a comma.
first_tuple = (4, “Hi”, 2)
Output: (4, Hi, 2)
Creating a nested tuple means nesting one tuple inside another.
first_tuple = (“Hi”, (3, 2, 9), (4, 7, 6))
Output: (Hi, ((3, 2, 9), (4, 7, 6))
You can access elements in tuples by using the index number inside the square brackets.
A tuple's index begins at 0, and the index operator [accesses it]. The index must be an integer and fall within the tuple range.
first_tuple = (1, 2, 7, 4, 7, 9, 2, 1, 5, 3)
x = first_tuple.index(7)
Output: Index of 7: 2
Negative indexes can also be used to access the tuple elements. In negative indexing, -1 refers to the last element, whereas -2 is used for the next-to-last, etc.
first_tuple = ('p', 'e', 'r', 'm', 'i', 't')
print(first_tuple[-1])
Output: 't'
print(first_tuple[-6])
Output: 'p'
In Python, the slicing operator colon ':' can also access a set of tuple items.
first_tuple = ('a', 'b', 'c', 'd')
print(first_tuple[1:]) #print index 1 elements to end
print(first_tuple[:2]) #print index 1 to index 2 elements
print(first_tuple[1:3]) #print index 1 to index 3 elements
print(first_tuple[::2]) #print elements from start to end using step sizes of 2
Output
('b', 'c', 'd')
('a', 'b')
('b', 'c')
('a', 'c')
By using a keyword, you can check whether a certain element is found in a tuple.
first_tuple = ('A', 'L’, 'E', 'M', 'S', 'X', 'I', 'F', 'D')
if 'A' in first_tuple:
print ("Yes, A exists in the tuple")
Output: Yes, A exists in the tuple
Considering that tuples are ordered and contain immutable elements, Python won’t let you update or modify the tuple. However, there’s a simple hack to change the element value of tuples using lists. The first step is to turn the tuple into a list. Then, you can update the list as you please and convert it to a tuple.
first_tuple = (2, 4, 6, 8)
print ("Original Tuple is:", first_tuple)
value = 10
print("Value to be added:", value)
newTuple = (10,)
second_tuple = first_tuple + newTuple
print("Updated tuple is:", )
Output:
Original Tuple is: (2, 4, 6, 8)
Value to be added: 10
Updated tuple is: (2, 4, 6, 8, 10)
Again, tuples are unchangeable, so adding new elements is impossible. But, you can use the same hack as that to update tuples to add new elements.
First_tuple = (2, 4, 6 )
print( "Old Tuple: ")
print( First_tuple)
temp = list( First_tuple)
temp.append(8)
First_tuple = tuple( temp )
print( " New Tuple: ")
print( First_tuple)
Output:
Old tuple
(2, 4, 6)
New Tuple:
(2, 4, 6, 8)
As tuples are immutable, it is impossible to delete any element from the tuple. However, you can use the “del” keyword to delete the entire tuple.
First_tuple = ( 1, 2, 3 )
print(First_tuple)
Output: (1, 2, 3 )
del (First_tuple)
Output: Error: ‘First_tuple’ not defined.
Here, it is evident that the tuple is removed since Python was unable to locate it after using "del."
When creating a tuple, you’re assigning several values — a process known as “packing a tuple.”
First_tuple = ( 2, 4, 6)
On the other hand, when extracting the values into variables, you’re “unpacking a tuple.”
First_tuple = ( 2, 4, 6 )
(two, four, six) = First_tuple
print( two )
print( four )
print( six)
# prints
Output:
2
4
6
Photo by Fatos Bytyqi on Unsplash
The data structure of a tuple is unchangeable, which increases its processing performance over lists. As a result, it optimizes Python projects and programs, making your Python scripts run more efficiently. Hopefully, our extensive coverage of the common properties and ways of tuples creation have helped your path to coding like a pro.