What are Tuples in Python with Syntax and Examples
In this tutorial we are going to learn about Tuples in Python with few examples.
In Python tuples are very similar to lists, however, unlike lists they are immutable meaning they can not be changed. You would use tuples to present things that shouldn’t be changed, such as days of the week, or dates on a calendar.
we will get a brief overview of the following:
- Constructing Tuples
- Basic Tuple Methods
- When to Use Tuples
You’ll have an intuition of how to use tuples based on what you’ve learned about lists. We can treat them very similarly with the major distinction being that tuples are immutable.
The construction of a tuples use () with elements separated by commas.
Create a tuple
t = (1,2,3)
Check len just like a list
Can also mix object types
t = ('one',2) ('one', 2)
Use indexing just like we did in lists
Slicing just like a list.
Tuples have built-in methods, but not as many as lists do.
Let’s look at two of them:
Use .index to enter a value and return the index.
Use .count to count the number of times a value appears.
Values of tuples cannot be changed.
- t= ‘change’-it gives you type error.
- t.append(‘one’)-it gives you attribute error.
You may be wondering, “Why bother using tuples when they have fewer available methods?” To be honest, tuples are not used as often as lists in programming, but are used when immutability is necessary.
If in your program you are passing around an object and need to make sure it does not get changed, then a tuple becomes your solution. It provides a convenient source of data integrity. You should now be able to create and use tuples in your programming as well as have an understanding of their immutability.