Today I will show some examples of Tuples in Python. Basically, a tuple is a collection of values. Unlike a list, a tuple is immutable. Also, the values in a tuple are separated by a comma. Therefore, if a tuple contains a single value, a comma should be there after the value. Moreover, a tuple is contained in round brackets as opposed to a list that is enclosed in square brackets. The following code shows how to create a tuple.
x=() print(x) y=(90,) print(y) z=(6,9,10) print(z) mylist=[1,2,3] w=(z,'abc',9.6,True,200, mylist) print(w)
As shown above, there are four tuples in the code. While the first one is an empty tuple, the second one has only one element. Also, a tuple can have elements of different types. Even, a tuple can be an element of another tuple. Likewise, a list can also be a member of a tuple.
So, the tuple in many ways similar to a list. Like a list it also allows duplicates. Further, the elements of a tuple are ordered. However, there are differences such as the tuple is immutable.
The following list provides some example of tuples in python.
- Perform four arithmetic operations and return the resulting values as a tuple.
- Basic examples using tuples in python.
- Create a List of Lists using a Tuple.
- An example to create a list of tuples in python.
- How to create a tuple of tuples in python.
Advantages of Tuples
- A tuple provides us a way to return multiple values from a function. therefore a return statement in s function in python can have multiple values separated by a comma. Further, all these values are assigned to a tuple when the function returns.
- Since tuples are immutable, they are more efficient than lists because of their fixed size.
- Also, we can use tuples in dictionaries because of having immutable values as the key.
- Another advantage of using tuples is that the data doesn’t change and write-protected.