Python is among the most popular and fastest growing high level, general-purpose programming language which works upon the interpretation method. The main reason behind its growth is its simple coding syntax and methods, which help in writing shorter and simpler codes as compared to other similar programming languages such as C++, Java, etc.
Although Python had been developed in the 1980s, it was commercially launched in 1991. One of the most interesting and surprising facts about languages is that usually the creators of a language are unknown but in the case of Python, we know its creator’s name. It was developed by Guido van Rossum and is currently managed by the Python Foundation. This language got its name from a very popular show, Monty Python's Flying Circus, a BBC comedy series from the 1970s.
Python is a multi-paradigm programming language that supports Object oriented programming and structured programming along with functional programming and aspect oriented programming. Unlike others, it uses white space indentation while other languages use curly brackets, keywords, etc for their indentation. This white space indentation is referred to as the off-side rule which was also used by some other languages but they usually don't have any semantic meaning. Its design emphasizes a lot on code readability by the significant use of white spaces so that everyone can easily understand the written code by anyone. Also, its object-oriented method approach helps in giving a tough competition to Java. In this article, we take you on an in-depth tutorial on Tuple in Python. We will learn the methods of tuple creation, accessing tuple, tuple functions in Python, etc.
There are several built-in data types in Python, such as List, Set, Dictionary, etc. Somewhat similar to arrays in C++, there is one such built-in data type called Tuple in Python. A tuple can be considered a data type that acts as a container or collection of different data types in an ordered and unchangeable manner. Unlike an array, these tuple in Python are written with round brackets. Even lists have a very similar character to that of a tuple, but the major difference between them is that after assigning the elements to a tuple, it can't be changed, but the elements of a list can be changed.
In a very short period, Python has not only proved itself to be a useful and popular programming language among the masses, but it has also become an inspiration for several other programming languages such as Boo, Cobra, GDScript, Groovy, Julia, Nim, Ruby, etc. These days Python is being extensively used in nearly every field for programming.
Tuple Items
The elements which we contain inside the parentheses are called tuple items, which can be of any type, i.e., integer, float, char, double, string, etc. Elements can be inserted inside a tuple during tuple creation, as shown in the above examples. But an important point to note is that elements can't be changed in a tuple in Python after getting assigned values.
Some unique properties of tuple items are as follows:
- Ordered: The tuple elements always stay in an ordered manner that can’t be changed after declaration. So, every programmer or coder needs to be very careful while placing the elements in a tuple to ignore any sort of errors during execution.
- Unchangeable: Elements can’t be changed in tuple in Python after declaration.
But if a tuple contains elements of a mutable data type such as list, then the nested items can be changed.
Eg.,
first_tuple = (3,1,8, [6,8])
first_tuple[3][0] = 7
print(first_tuple)
# Here the first element of list will be changed and printed.
Output :
(3, 1, 8, [7, 8])
Also, although the values of a tuple can’t be changed, they can be reassigned according to the changed or updated circumstances.
Eg.,
first_tuple = (1, 2, 3, 4)
print(first_tuple)
Output :
(1, 2, 3, 4)
If we wish to reassign, then
first_tuple = (5,6,7,8)
print(first_tuple)
# Here new values will be assigned to the tuple first_tuple.
Output :
(5, 6, 7, 8)
Eg.,
first_tuple = (1,8,8,4,4)
print(first_tuple)
Output :
(1, 8, 8, 4, 4)
Tuples Items – Data Types
A tuple can accept data of any data type such as integer, float, double, string, etc.
Eg.,
first_tuple1 = (“mango”, “guava”, “banana”)
first_tuple2 = (1,8,4,5,)
first_tuple3 = (True, False, False)
print(first_tuple1)
print(first_tuple2)
print(first_tuple3)
Output :
('mango', 'guava', 'banana')
(1, 8, 4, 5)
(True, False, False)
How to add tuples in Python
A tuple in Python can be created by placing all the desired elements inside the round brackets (), which should be separated by comma ',.' Even though the parentheses, i.e., round brackets are optional, it's a good practice to use them to increase the readability of the code.
Unlike arrays in C++, tuples can have different types of data in a single parenthesis and hence can be classified as different types. Here are some examples with their output:
1. Empty Tuple: A tuple with no values
Eg.,
first_tuple = ()
print(first_tuple)
Output :
()
2. Tuple Having Integers
Eg.,
first_tuple = (5, 4, 8, 9)
print(first_tuple)
Output :
(5, 4, 8, 9)
3. Mixed Tuple: A tuple that has different data types like float, int, string, etc.
Eg.,
first_tuple = (5, “Python”, 8)
print(first_tuple)
Output :
(5, ‘Python’, 8)
4. Nested Tuple: Single or more tuples inside a tuple.
Eg.,
first_tuple = (“Python”, (4, 6, 8), (1, 3, 5))
print(first_tuple)
Output :
(‘Python’, (4, 6, 8), (1, 3, 5))
If a tuple is created without using any parentheses, it is called tuple packing.
Eg.,
first_tuple = 7, 8, 9, “creation”
print(first_tuple)
Output :
(7, 8, 9, ‘creation’ )
Tuple packing can also be unpacked.
Eg.,
a, b, c = first_tuple
print(a)
print(b)
print(c)
Output :
7
8
9
creation
If you want to create a tuple with just one element, then you should remember to put a trailing comma to classify it as a tuple.
Eg.,first_tuple = (50,)
print(first_tuple)
Output :
(50, )
Accessing tuple items
Tuple elements can be accessed by various methods, which are as follows:
1. Indexing
The index in a tuple starts from 0, accessed by the index operator []. The index can't be any other value except integer, which should be in the tuple range index.
For, e.g.,
To access elements in the following tuple.
first_tuple = (2, 8, 6, 4, 3, 5, )
print(first_tuple[2])
print(first_tuple[4.6])
print(first_tuple[7])
Output :
6
#TypeError
#IndexError
2. Negative Indexing
The elements of tuples in Python can also be accessed by using negative indexing, such as -1 for the last element, -2 for the second last, and so on.
For Eg.,
To access elements in the following tuple.
first_tuple = (2, 8, 6, 4, 3, 5, )
print(first_tuple[-2])
# Here the second last element in the tuple will be printed.
Output :
3
3. Slicing
In Python, you can also access a range of tuple items using slicing operator colon ':’
For, e.g.,
To access elements in the following tuple.
first_tuple = (2, 8, 6, 4, 3, 5, )
print(first_tuple[2:4])
# Here the elements from index 2 to 3 will be printed.
Output :
(6, 4)
Tuple Length
Tuple functions in Python have a dedicated function to determine the length of tuple, i.e., the no. of elements a tuple contains. len() function is used to determine the length of a tuple.
For eg.,
first_tuple = (5,6,7,5,8,)
print(len(first_tuple))
#It will show the no of indexed elements in the tuple first_tuple.
Output :
5
type()
In Python, tuples can be defined as objects with ‘tuple’ as their data type. Type () function is used to find the data type of the tuple. It’s an important tuple function in Python. It helps in the correction of minor mistakes; such as creating a tuple with a single element and forgetting to add the comma ',' at the end of the single element. This example will not be considered as a tuple by Python.
The following examples will clarify this concept.
Eg.,
first_tuple1 = (5)
first_tuple2 = (5,)
print(type(first_tuple1))
print(type(first_tuple2))
#Although these tuples look similar, their output will vary due to a single comma.
Output :
<class ‘int’>
<class ‘tuple’>
The tuple() Constructor
The tuple() constructor is a tuple method in Python that makes the construction of a tuple by using a constructor. The use of a tuple constructor will be clear from the given example; notice the double brackets.
Eg.,
first_tuple = tuple((1, “story”, 5))
print(first_tuple)
Output :
(1, ‘story’, 5)
Deleting a tuple
The most problematic drawback of a tuple in Python is that once created, it cannot be changed. However, it can be deleted entirely by using the keyword 'del.' The use of this keyword is illustrated below.
Eg.,
first_tuple = (50,)
print(first_tuple)
Output :
(50)
Now, let’s use the keyword del
del (first_tuple)
print(first_tuple)
Output :
NameError : name ‘first_tuple’ is not defined.
Here, we can clearly see after using the keyword ‘del’, Python was unable to find the tuple declared earlier which shows that the tuple has been deleted entirely.
Tuple Membership Test
In Python, we can check to verify whether an element is a member of the tuple or not by using the keyword 'in,' which returns the result in a Boolean form like True or False. Its use is illustrated below.
Eg.,
first_tuple = (1,5,6,89,7)
print(1 in first_tuple)
print(2 in first_tuple)
Here, these codes will check and verify whether 1 and 2 are a part of the tuple first_tuple and will provide an output as follows:
Output :
True
False
For Loop in a Tuple
A for loop can be used to obtain a simultaneous output with the continuous elements of a tuple. Suppose you want to print the name of members of a group with a 'Hello!', in such a case it could be very useful. It would be clear from the following example.
Eg.,
for name in (‘Aditya’, ‘Aditi’)
print(“Hello”, name)
Output :
Hello Aditya
Hello Aditi
Python Collections (Arrays)
Collection data types play a major role in any programming language as they are pretty useful for storing large collections of data under a single variable. In Python, we have 4 different types of collection data types, which are explained below.
In the case of the list in Python, the elements are placed in an ordered manner, which can be modified; that is, its elements can be changed, added, or deleted as per the need, and it also allows duplicate values.
We have studied this collection data type so far and learned its several properties, methods, and functions. It is an ordered collection that cannot be changed but allows duplicate entries.
A set in Python is a collection data type that is unordered and unindexed, and also, it does not allow any duplicate entries. It is useful for collecting those data that need to have some unique identifier such as ID, Roll No, etc.
Dictionary is a collection data type that is somewhat similar to set but has a slight variation: it is indexed, and hence its values can be changed easily. Also, it is ordered and doesn't contain any duplicate members.
Top Cities Where KnowledgeHut Conduct Python Certification Course Online
Conclusion
This article helped you understand the nuances of the collective data type Tuple in Python, such as its properties, functions, methods, applications, etc., with various examples and codes. Also, we came across other similar collective data types such as set, dictionary, and list, which are also available in Python and have their specific properties and functions and are hence used accordingly.
Now the question arises that which collective data type we should use in our programs so that it results in a beautifully written and well readable code that everyone can easily understand.
As is clear from our discussion, every data type has its properties and has its own weak as well as strong points. So, anyone should keep those points in mind, while selecting the correct collective data type for them.
For instance, if someone wants to have a collection with unique entries, they should go with a set or dictionary. To have the freedom to change the item at convenience, you should choose a dictionary. Further, if one wants to have an indexed and ordered arrangement that must contain duplicate entries, such as for entering marks of a student, they should choose a list or tuple.
Python tuple is a pretty useful tool for coders to code with ease and comfort. It has several advantages and benefits for easily developing a program. Try some hands-on coding with this marvelous language and have fun playing with the codes while exploring the unknown paths. Develop innovative applications that may prove your worth as a formidable Python coder.