Python Tuple Operations
Python Tuple is an immutable collection of items. Also, tuple is an ordered collection. These properties of a tuple enable some operations like accessing the items using an index, iterating over its elements, etc., and disable some of the operations like updating tuple items.
In this tutorial, we will go through some of the commonly tuple operations in Python programming.
Create a Tuple
To create a tuple, you can provide the comma separated items enclosed in parenthesis or use tuple() builtin function. tuple() accepts an iterable and converts the iterable into tuple.
In the following program, we will create a tuple in two ways: using parenthesis and tuple() builtin function.
tuple1 = ('a', 'e', 'i', 'o', 'u') tuple2 = tuple(['a', 'e', 'i', 'o', 'u'])
Access Tuple Items
Tuple is an ordered collection. So, you can access its items using index, just like a Python List.
tupleX = ('a', 'e', 'i', 'o', 'u') print(tupleX) print(tupleX) print(tupleX) print(tupleX) print(tupleX)
a e i o u
The index starts at 0 for the first item, and increments for the subsequent items.
You can also use negative indexing. To learn more about accessing items of tuple, refer Python Access Tuple.
Iterate over Tuple Items
Tuple returns an iterator, and you can use for loop to iterate over the items. Or using the index and while loop, you can iterate over tuple items.
tupleX = ('a', 'e', 'i', 'o', 'u') for item in tupleX: print(item) tupleY = (5, 6, 3, 2) index = 0 while index < len(tupleY): print(tupleY[index]) index += 1
a e i o u 5 6 3 2
List of all Tuple Operations
Following are the list of tuple operations that we can perform in Python. Each of these tutorial provide well detailed examples to understand each operation.
- Tuple – Detailed tutorial on what a tuple is?
- Create Tuple – Different ways to create a Tuple.
- Empty Tuple – No items in Tuple
- Tuple Length – Find the number of elements in a tuple.
- Access Tuple – Access items of tuple using index or loop.
- Iterate over Tuple items using For Loop
- Iterate over Tuple items using While Loop
- Update Tuple Items – A workaround, since tuple is immutable.
- Check if Item is in Tuple
- List of Tuples – Tutorial on how to create a list of tuples in Python. The list will contain tuples as elements.
- Sort List of Tuples – We have a list of tuples, and the tutorial helps on how to sort these list of tuples.
- Tuple vs List – Differences between a Tuple and List in Python.
- Return Tuple from Function – How to return a Tuple from a Function.
- Convert Tuple to List – Tutorial on how to convert a Tuple into a List.
- Convert List to Tuple – Tutorial on how to convert a List into a Tuple.
- Convert Tuple to String – Tutorial on how how to convert a Tuple into a String.
In this tutorial of Python Examples, we learned how to use Tuple in a Python program with different usages of tuple presented as examples and tutorials.