English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Tuples in Python are similar tolist.The difference between the two is that once a tuple is assigned, its elements cannot be changed, whereas in a list, elements can be changed.
Create a tuple by placing all items (elements) inside parentheses () (separated by commas). Parentheses are optional, but, it is a good habit to use them.
Tuples can have any number of items and can have different types (integers, floats, lists,stringetc.).
Tuples can also be created without using parentheses. This is called tuple packing.
Creating a tuple with one element is a bit special.
A tuple with a single element is a bit special. The bracket containing only one element is not enough. We need a comma at the end to indicate that it is actually a tuple.
my_tuple = ("hello") print(type(my_tuple)) # <class 'str'> # Create a tuple with a single element my_tuple = ("hello",) print(type(my_tuple)) # <class 'tuple'> # Parentheses are optional my_tuple = "hello", print(type(my_tuple)) # <class 'tuple'>
We can access tuple elements in many ways.
We can use the index operator [] to access items in the tuple starting from index 0.
therefore, a tuple with6an element tuple will have indices from 0 to5to access the index of the tuple. Try to access an element outside the tuple (for example6,7 ...) will raise an IndexError.
The index must be an integer; therefore, we cannot use float or other types. If we do, it will cause a TypeError.
Similarly, access nested tuples using nested indexing, as shown in the following example.
my_tuple = ('p', 'e', 'r', 'm', 'i', 't') print(my_tuple[0]) # 'p' print(my_tuple[5]) # 't' # IndexError: List index out of range # print(my_tuple[6]) # The index must be an integer # TypeError: List index must be an integer, not a float # my_tuple[2.0] # Nested tuple n_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) # Nested indexing print(n_tuple[0][3]) # 's' print(n_tuple[1][1]) # 4
Python allows negative indexing on sequences.
Index-1It represents the last item,-2It represents the second-to-last item, and so on.
my_tuple = ('p', 'e', 'r', 'm', 'i', 't') # Output: 't' print(my_tuple[-1]) # Output: 'p' print(my_tuple[-6])
We can use the slicing operator-The colon ':' accesses a series of items in the tuple.
my_tuple = ('p','r','o','g','r','a','m','i','z') # The2elements-4elements # Output: ('r', 'o', 'g') print(my_tuple[1:4]) # From the beginning to the second element # Output: ('p', 'r') print(my_tuple[:-7]) # The8elements to the end # Output: ('i', 'z') print(my_tuple[7:]) # Elements from the beginning to the end # Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(my_tuple[:])
By considering the index between elements, slicing can be visualized best as shown below. Therefore, to access a range, you need to use the index of the partial slice in the tuple.
Unlike lists, tuples are immutable.
This means that once the elements of the tuple are assigned, they cannot be changed. However, if the elements themselves are mutable data types (such as lists), their nested items can be changed.
We can also assign tuples to different values (reassign).
my_tuple = (4, 2, 3, [6, 5]) # TypeError: 'tuple' object does not support item assignment # my_tuple[1] = 9 # But, items of mutable elements can be changed my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5]) print(my_tuple) # Tuples can be reassigned my_tuple = ('p','r','o','g','r','a','m','i','z') # Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(my_tuple)
We can use+operator to merge two tuples. This is also known asConcatenation.
We can also use the operator*to repeat the elements in the tupleRepeattimes given.
whichever+and*This operation will result in a new record.
# Concatenation # Output: (1, 2, 3, 4, 5, 6) print(((1, 2, 3) + (4, 5, 6)) # Repeat # Output: ('Repeat', 'Repeat', 'Repeat') print(("Repeat",) * 3)
As mentioned above, we cannot change the elements in a tuple. This also means that we cannot delete or remove items from the tuple.
However, you can use the keyworddelCompletely delete a tuple.
my_tuple = ('p','r','o','g','r','a','m','i','z') # Cannot delete items # TypeError: 'tuple' object does not support item deletion # del my_tuple[3] # Can delete the entire tuple del my_tuple # NameError: Name 'my_tuple' is not defined print(my_tuple)
Tuples do not provide methods to add or delete items. Only the following two methods are available.
Method | Description |
---|---|
count(x) | Returns the number of itemsx |
index(x) | Returns equal toxThe index of the first item |
Some examples of Python tuple methods:
my_tuple = ('a', 'p', 'p', 'l', 'e',) print(my_tuple.count('p')) # Output: 2 print(my_tuple.index('l')) # Output: 3
We can use the keyword 'in' to test whether an item exists in the tuple.
my_tuple = ('a', 'p', 'p', 'l', 'e',) # In operation # Output: True print('a' in my_tuple) # Output: False print('b' in my_tuple) # Not in operation # Output: True print('g' not in my_tuple)
Using a for loop, we can traverse each item in the tuple.
# Output: # Hello John # Hello Kate for name in ('John', 'Kate'): print("Hello", name)
Since tuples are very similar to lists, they are also used in similar situations.
However, there are some advantages to implementing tuples on lists. The following lists some of the main advantages:
We usually use tuples for heterogeneous (different) data types and lists for homogeneous (similar) data types.
Since tuples are immutable, it is faster to traverse a tuple than to use a list. Therefore, there is a slight performance improvement.
Tuples containing immutable elements can be used as dictionary keys. This is not possible for lists.
If you have immutable data, implementing it as a tuple will ensure that it remains write-protected.