Hello everyone, welcome to our next blog post on tuples in Python! In our last article, we covered everything you need to know about Python lists. In this post, we will be discussing a similar but distinct datatype in Python called tuples. Tuples are often used to group related pieces of data together, and they have some unique properties and use cases that we will explore in detail. So, let’s dive into the world of Python tuples!
Tuple is one of the most important and frequently used data types in python just like lists.
Â
Think of a tuple as a list of items that you can’t change once you’ve made it. So, let’s say you want to make a list of your favorite foods. You could create a tuple with all your favorite foods listed in order, separated by commas and enclosed in parentheses.Â
Â
foods = (‘noodles’, ‘apple’, ‘steak’, ‘mangoes’)
Â
Once you’ve created the tuple, you can’t add or remove items from it – it’s set in stone.
Â
The nice thing about tuples is that they’re really good for representing data that shouldn’t be changed. For example, you might use a tuple to store information about a person, like their name, age, and address. Since this information shouldn’t be changed, using a tuple to hold it makes sense.
There are several ways to create tuples in python, one of the most general way to create a tuple is by using a sequence of values enclosed in parentheses and separated by commas.
Â
For example, to create a tuple with three elements – “apple”, 42, and True – you would write:
my_tuple = (“apple”, 42, True)
We should also note that In Python, the parentheses used to define a tuple are not strictly necessary. What’s important are the commas used to separate the individual elements of the tuple. Here’s an example:
Here we can see that this is a valid tuple definition, even though there are no parentheses around the elements.
However, while it’s technically allowed to omit the parentheses, it’s generally considered good practice to include them to make the code more readable and less prone to errors.
Creating a tuple with a single element is a bit tricky in Python. As we mentioned earlier, you need to enclose the element in parentheses. However, if you simply write ‘(element)’, it will not create a tuple, but rather just return the element itself.
To create a tuple with a single element, you need to add a comma after the element. Here’s an example:
In this example, we’ve created a tuple with a single element – the string “lizard”. Note the comma after the element – this is what makes it a tuple. If we had writtenÂ
my_tuple = (“lizard”) instead, it would not have created a tuple, but rather just assigned the string “apple” to the variable my_tuple.
Â
One major way to create a tuple in Python is to use the tuple() function. This function can be used to convert any iterable object (such as a list or a string) into a tuple. Here’s the syntax of tuple function:
Â
tuple(iterable)
Â
Here, iterable is any iterable object (such as a list, a string, a set, or a dictionary). The tuple() function takes the elements of the iterable and creates a new tuple containing those elements.
Â
Here are few examples:
1. List to tuple
In this code, we’ve created a list ‘my_list’ containing four integers, and then used the tuple() function to convert it into a tuple ‘my_tuple’. The resulting tuple would be (1, 2, 3, 4).
Â
In this code, we’ve created a string ‘my_string’ containing the word “hello“, and then used the tuple() function to convert it into a tuple ‘my_tuple’. The resulting tuple would beÂ
Â
(‘h’, ‘e’, ‘l’, ‘l’, ‘o’).
Â
Similarly, as shown above we can convert all sorts of data types like integer, range, dictionary etc to tuple() using the tuple function.
Â
Â
we can get user input as a tuple in Python using the input() function and the tuple() function.
Â
Here’s an example code that asks the user to enter two values separated by a space, and then converts them into a tuple:
In this code, the input() function is used to prompt the user to enter two values separated by a space. The split() function is then used to split the user input into a list of strings. Finally, the tuple() function is used to convert the list into a tuple, which is then printed to the console.
Â
You can also use the eval() function to get user input as a tuple in Python similar to how we did with strings. The eval() function as mentioned in our previous blogs takes a string argument and evaluates it as a Python expression. You can use this to create a tuple from a string entered by the user.
Â
Â
Here’s an example code that asks the user to enter a tuple as a string, and then converts it into a tuple using the eval() function:
In this code, the input() function is used to prompt the user to enter a tuple as a string. it is then passed to the eval() function which evaluate the string as a Python expression, which creates the tuple. Finally, the tuple is printed to the console.
Â
Comprehension is a concise and powerful syntax in Python that allows you to create new sequences (lists, sets, dictionaries, or tuples) based on existing sequences. They are a combination of loops and conditional statements that make it easy to create new sequences in a single line of code.
Â
Suppose you want to create a tuple containing all odd numbers up to 100. Writing each number one by one inside the tuple would be time-consuming. However, using tuple comprehension, you can achieve this task easily in a single line of code.
Â
Example: odd_numbers = tuple(i for i in range(1, 101) if i % 2 != 0)
Â
In this code, we are using tuple comprehension to iterate over a range of numbers from 1 to 100, and selecting only the odd numbers using a conditional statement (if i % 2 != 0). The resulting tuple will contain all the odd numbers from 1 to 100.
Just like in lists, accessing elements in a tuple is an essential operation in Python programming. Tuples support multiple ways of accessing elements, including indexing, slicing, negative indexing, and more. In this section, we will discuss the most common ways to access elements in a tuple, which will enable you to manipulate the data inside the tuple efficiently.
Â
It is the process of accessing an individual element of a tuple by its position or index. Indexing in Python starts from 0, which means that the first element in a tuple is at index 0, the second element is at index 1, and so on.Â
To access a specific element in a tuple using indexing, you can use the square brackets [] notation with the index number of the element you want to access.Â
For example, if you have a tuple my_tuple with three elements, you can access the first element using my_tuple[0], the second element using my_tuple[1], and the third element `using my_tuple[2].
In conclusion, we can say that indexing is a fundamental way of accessing individual elements of a tuple in Python. By using the index number of an element in a tuple, you can retrieve its value quickly and easily. However, it is essential to keep in mind that indexing in Python starts from 0, and attempting to access an index that does not exist will result in an error.
Â
Negative indexing just like normal indexing is a way of accessing elements in a tuple by their position, but from the end of the tuple rather than the beginning. In this process the last element of a tuple has an index of -1, the second to last element has an index of -2, and so on.
To access an element in a tuple using negative indexing, you can use the square brackets notation [] just like in normal indexing but with a negative index number. For example, if you have a tuple my_tuple with three elements, you can access the last element using my_tuple[-1], the second to last element using my_tuple[-2], and the third to last element using my_tuple[-3].
Negative indexing is significant because it allows us to access elements in a tuple from the end rather than the beginning, which can be helpful when we don’t know the length of the tuple. It is also useful in situations where we need to access the last few elements of a tuple without knowing the exact position of those elements. For example, if we have a tuple of data and we want to retrieve the last two elements, we can use negative indexing to access them easily. Overall, negative indexing is an essential feature of Python tuples and can be useful in various programming scenarios.
Â
Slicing is a way of accessing a range of elements in a tuple by specifying the start and end indices. The basic syntax of slicing is using the colon : inside the square bracket’s notation [] with two integer values representing the start and end indices.Â
Â
The start index is included in the slice, but the end index is not. For example, if we have a tuple my_tuple with five elements, we can create a slice of the first three elements using my_tuple[0:3]. This will return a new tuple containing the first three elements (indexes 0,1 and 2) of my_tuple.
Â
Syntax: my_tuple[start_index:end_index:step]
Â
In addition to the start and end indices, we can also specify a step value for the slice. The step value determines the increment between the elements included in the slice. Default step value is 1, which means that all elements between the start and end indices will be included.Â
Â
Note: if you omit start_index, Python assumes that you want to start the slice from the beginning of the tuple.Â
Â
If you omit end_index, Python assumes that you want to slice until the end of the tuple.Â
Â
In case of omitting  step, Python assumes that you want to select every element of the slice (i.e., a step of 1).
Â
Slicing is a powerful feature of Python tuples that can be useful in various programming scenarios, such as extracting a subset of data from a tuple, iterating over a subset of elements, or reversing the order of elements in a tuple.
Â
Just like nested lists, we can have nested tuples in Python as well. Nested tuples are tuples that contain other tuples as elements. To access elements of a nested tuple, we use a similar indexing technique as for nested lists.
Â
The syntax for accessing elements of a nested tuple is similar to that of accessing elements of a nested list. We use square brackets [] to access elements and the index numbers to identify the position of the element.
Â
For a nested tuple, we use multiple indexing operations separated by square brackets to access an element. The first index refers to the position of the tuple inside the main tuple, and the second index refers to the position of the element inside the inner tuple.
In this example, my_tuple[2] returns the third tuple (5, 6), and my_tuple[2][1] returns the second element 6.
Â
We can use as many index operations as needed to access elements of deeper nested tuples.
Now that we’ve covered the basics of tuples, it’s time to explore the various operations that can be performed on them. Just like lists, tuples support a range of useful operations that can help you manipulate and analyse your data. In this section, we’ll cover some of the most common tuple operations, including concatenation, repetition, membership testing, sorting, and more. So, without further ado, lets dive in.
Â
Concatenation is the process of combining two or more tuples to form a new tuple. In Python, we can concatenate tuples using the ‘+‘ operator. When we concatenate two tuples, a new tuple is created that contains all the elements of both tuples.
Here is an example of how concatenation is done in tuples.
In the example above, we have two tuples, tuple1 and tuple2 containing some elements. We concatenate them using the + operator and assign the result to a new tuple tuple3. The resulting tuple tuple3 contains all the elements of both tuples tuple1 and tuple2.
Note that tuples are immutable, so the + operator creates a new tuple and does not modify the original tuples.
Â
In addition to concatenating tuples, another common operation is to repeat a tuple multiple times. This can be useful in certain situations, such as when you need to create a tuple of a certain length with repeated elements.
Â
To repeat a tuple in Python, you can use the multiplication operator. The syntax is as follows:
Â
Syntax: new_tuple = original_tuple * n
where ‘original_tuple’ is the tuple you want to repeat and ‘n’ is the number of times you want to repeat it. The result will be a new tuple that contains n copies of the original tuple.
Â
Here’s an example:
In this example, we create a tuple ‘t1’ with three elements. Then, we repeat it three times using the multiplication operator to get a new tuple ‘t2’ that contains nine elements. Finally, we print the result using the print() function.
Â
Membership testing is the process of checking whether an element is present in a sequence or not just like we have discussed in case of strings and lists.Â
In Tuples, membership testing can be done using the ‘In’ and ‘not in’ operators. These operators return a Boolean value, True or False, depending on whether the element is present in the sequence or not.Â
Here’s an example of membership testing in a tuple:
In this example, we first create a tuple ‘my_tuple’ containing the numbers 1 through 5.Â
Â
We then use the ‘in’ operator to check if the value 3 exists in the tuple. Since 3 is indeed an element in the tuple, the output is True.
Â
Next, we use the ‘not in’ operator to check if the value 6 does not exist in the tuple. Since 6 is not an element in the tuple, the output is also True.
Â
This technique is very useful when we want to search for an element in a tuple without writing a loop to iterate through the tuple.
Â
In this section, we will discuss how to find the length of a tuple in Python. The length of a tuple is the total number of elements present in it. We can use the built-in ‘len()’ function to find the length of a tuple.
Â
It takes the tuple as an argument and returns the number of elements in the tuple.
Syntax: len(sequence)
Here, sequence can be any sequence object such as a tuple, list, string, etc.
In the above example we created a tuple ‘my_tuple’ with 5 elements, then uses the len() function to get its length and assigns it to a variable ‘length’. Finally, we printed the value of length, which is 5.
Â
Tuples are immutable, meaning that their values cannot be changed after they are created. Therefore, you cannot sort a tuple in-place like you can with a list.Â
Â
However, you can create a new sorted tuple based on an existing tuple.
Â
To sort a tuple, you can use the built-in sorted() function. This function takes an iterable (in this case, a tuple) and returns a new sorted list. If you want the result to be a tuple instead of a list, you can use the tuple() function to convert the list back to a tuple.
Â
Here’s an example:
In this example, we create a new tuple called sorted_tuple by first calling the sorted() function on my_tuple, which returns a sorted list. We then pass this sorted list to the tuple() function, which converts it back to a tuple. Finally, we print the sorted tuple.
Â
Sorting in descending order:
The sorted() function sorts elements in ascending order by default. However, you can use the reverse parameter as we did with the lists to sort the elements in descending order. For example:
In this example, we pass ‘reverse=True’ to the sorted() function to sort the elements in descending order.
Reversing a tuple means changing the order of the elements in the tuple such that the last element becomes the first element and the first element becomes the last element. This can be achieved in Python using the slicing technique or the ‘reversed()’ function.
Â
To reverse a tuple, we can use the slice notation with a step value of -1. This step value tells Python to start from the last element of the tuple and move backward with a step of -1.
For example:
In the example above, we first create a tuple ‘my_tuple’ with the values (1, 2, 3, 4, 5). We then use the slice notation [::-1] to create a new tuple ‘reversed_tuple’ with the same elements as my_tuple, but in reverse order. Finally, we print the reversed_tuple which gives us the output (5, 4, 3, 2, 1).
Â
In Python, we know that tuples are immutable data types, so we can’t change their content directly. However, we can reverse a tuple by creating a new tuple with the reversed order of the original tuple.
Â
One way to do this is to use the reversed() function and convert the output into a tuple using the tuple() function.Â
For example:
In this example, we first define an ‘original_tuple’ with five elements.Â
Â
We then apply the ‘reversed()’ function to it, which returns a reverse iterator. Finally, we convert the reverse iterator to a tuple using the ‘tuple()’ function, and assign it to the ‘reversed_tuple’ variable.
Â
Now, the ‘reversed_tuple’ contains the same elements as ‘original_tuple’, but in reversed order.
Â
These are some of the major operations in tuples that we can perform in python. Now let us look at the various methods or functions that is related to the data type tuples in python.
Tuples, as we have discussed earlier, are immutable sequences in Python. Since they are immutable in nature, changing an original tuple once it has been created is not possible. Hence, there are only a few built-in methods for tuples in Python. In this section, we will explore two of the most commonly used tuple methods: count() and index(). These methods can help us manipulate and retrieve information from tuples efficiently. Let’s take a closer look at how they work.\
Â
The count() method in Python is a built-in method for tuples, lists, and strings. The count() method returns the number of times a specified element appears in the tuple.
The syntax for using the count() method is as follows:
Â
Syntax: tuple.count(element)
Â
Let’s see an example of how to use the count() method with tuples:
In the example above, we have a tuple named ‘my_tuple’ that contains three occurrences of the value 3. We use the count() method to count the number of occurrences of 3 in ‘my_tuple’. The output will be 3, which is the number of times 3 appears in ‘my_tuple’.
Â
The Python index() method is designed to return the index of the first instance of a given element within a tuple. When the specified element is not found in the tuple, a ValueError will be raised. The method can be used with the following syntax:
Â
Syntax: tuple.index(element, start, end)
Here’s an example:
In the above example, the index() method returns the index of the first occurrence of 20 in the tuple.
Alright guys that brings us to our last topic, the immutable nature of tuples. In this blog post we have covered all the basics you guys need to know about tuples, starting from how to create them to the various methods that are present in tuple. Now let us look at the immutable nature of tuples and what its significance are in python.
Â
Tuples in Python are immutable data structures, which means that once a tuple is created, its contents cannot be changed. This is in contrast to lists, which are mutable and can be modified after creation.
Â
One of the main advantages of the immutability of tuples is that they are more secure and less prone to bugs. Since tuples cannot be modified, it is easier to reason about the state of a program that uses tuples. Tuples are also more memory efficient than lists, as they require less overhead for each element.
Â
However, the immutability of tuples can also be a disadvantage in certain situations. Since tuples cannot be modified, it can be more difficult to perform operations that require changes to the underlying data. For example, if you need to sort a list of tuples based on a certain element, you may need to create a new list of tuples with the sorted elements.
Tuples are commonly used in Python programming in situations where immutability is desirable. For example, if you need to represent a fixed set of values, such as the days of the week or the months of the year, a tuple is a good choice. Tuples are also useful for returning multiple values from a function, since the values cannot be modified by the caller. Finally, tuples can be used as keys in dictionaries, since their immutability guarantees that the keys will not change over time.
Great, we have covered the fundamentals of tuples in Python. We have learned how to create tuples, access tuple elements using indexing, slicing, and negative indexing, as well as the various operations that can be performed on tuples. We also covered the two built-in methods, count() and index(). Lastly, we discussed the immutable nature of tuples and its advantages and disadvantages. I hope this blog has helped you understand the basics of tuples in Python. In our next blog post, we will be covering another major data type in Python, dictionaries. Stay tuned and thank you for taking the time to read. That’s a wrap, thanks for reading and visit 1stepgrow.
We provide online certification in Data Science and AI, Digital Marketing, Data Analytics with a job guarantee program. For more information, contact us today!
Courses
1stepGrow
Anaconda | Jupyter Notebook | Git & GitHub (Version Control Systems) | Python Programming Language | R Programming Langauage | Linear Algebra & Statistics | ANOVA | Hypothesis Testing | Machine Learning | Data Cleaning | Data Wrangling | Feature Engineering | Exploratory Data Analytics (EDA) | Â ML Algorithms | Linear Regression | Logistic Regression | Decision Tree | Random Forest | Bagging & Boosting | PCA | SVM | Â Time Series Analysis | Natural Language Processing (NLP) | NLTK | Deep Learning | Neural Networks | Computer Vision | Reinforcement Learning | ANN | CNN | RNN | LSTM | Facebook Prophet | SQL | MongoDB | Advance Excel for Data Science | BI Tools | Tableau | Power BI | Big Data | Hadoop | Apache Spark | Azure Datalake | Cloud Deployment | AWS | GCP | AGILE & SCRUM | Data Science Capstone Projects | ML Capstone Projects | AI Capstone Projects | Domain Training | Business Analytics
WordPress | Elementor | On-Page SEO | Off-Page SEO | Technical SEO | Content SEO | SEM | PPC | Social Media Marketing | Email Marketing | Inbound Marketing | Web Analytics | Facebook Marketing | Mobile App Marketing | Content Marketing | YouTube Marketing | Google My Business (GMB) | CRM | Affiliate Marketing | Influencer Marketing | WordPress Website Development | AI in Digital Marketing | Portfolio Creation for Digital Marketing profile | Digital Marketing Capstone Projects
Jupyter Notebook | Git & GitHub | Python | Linear Algebra & Statistics | ANOVA | Hypothesis Testing | Machine Learning | Data Cleaning | Data Wrangling | Feature Engineering | Exploratory Data Analytics (EDA) | Â ML Algorithms | Linear Regression | Logistic Regression | Decision Tree | Random Forest | Bagging & Boosting | PCA | SVM | Â Time Series Analysis | Natural Language Processing (NLP) | NLTK | SQL | MongoDB | Advance Excel for Data Science | Alteryx | BI Tools | Tableau | Power BI | Big Data | Hadoop | Apache Spark | Azure Datalake | Cloud Deployment | AWS | GCP | AGILE & SCRUM | Data Analytics Capstone Projects
Anjanapura | Arekere | Basavanagudi | Basaveshwara Nagar | Begur | Bellandur | Bommanahalli | Bommasandra | BTM Layout | CV Raman Nagar | Electronic City | Girinagar | Gottigere | Hebbal | Hoodi | HSR Layout | Hulimavu | Indira Nagar | Jalahalli | Jayanagar | J. P. Nagar |Â Kamakshipalya | Kalyan Nagar | Kammanahalli | Kengeri | Koramangala | Kothnur | Krishnarajapuram | Kumaraswamy Layout | Lingarajapuram | Mahadevapura | Mahalakshmi Layout | Malleshwaram | Marathahalli | Mathikere | Nagarbhavi | Nandini Layout | Nayandahalli | Padmanabhanagar | Peenya | Pete Area | Rajaji Nagar | Rajarajeshwari Nagar | Ramamurthy Nagar | R. T. Nagar | Sadashivanagar | Seshadripuram | Shivajinagar | Ulsoor | Uttarahalli | Varthur | Vasanth Nagar | Vidyaranyapura | Vijayanagar | White Field | Yelahanka | Yeshwanthpur
Mumbai | Pune | Nagpur | Delhi | Gurugram | Chennai | Hyderabad | Coimbatore | Bhubaneswar | Kolkata | Indore | Jaipur and More