Python Tuples
Python Tuples
Python Tuples are read-only lists. A tuple is an ordered sequence of items. A tuple can consist of several values separated by commas.
Lists and tuples are two types of data structures in Python. The primary difference between them is that tuples are immutable, meaning that once they are created, they cannot be modified. In contrast, lists are mutable and can be changed dynamically. Tuples are often used to write and protect data because their immutability ensures that the data cannot be accidentally modified. Additionally, tuples are usually faster than lists because of their fixed structure.
List vs. Tuple
Python List |
Python Tuple |
Lists are mutable. We can change the elements in the list. | Tuples are immutable. Tuples are read-only; we cannot change the elements in the tuple. |
Lists are declared using [], and elements are separated with commas. | Tuples are declared using (), and elements are separated with commas. |
Tuple declaration
Unlike lists, tuples are enclosed within parenthesis (). Tuples are declared as follows.
>>> tup = (2,4,6,8,10,12)
>>>
>>> type(tup)
<class ‘tuple’>
>>>
>>> print(tup)
(2, 4, 6, 8, 10, 12)
>>>
Using the slicing operator with a Tuple
The slicing operator[] is used to extract items from the tuple. However, we cannot edit data into the tuple.
>>> # Python Slice operator on Tuple
>>> # Define a tuple
>>> t = (2,4,6,8,10,12,14,3.14)
>>>
>>> print(t) # print the tuple
(2, 4, 6, 8, 10, 12, 14, 3.14)
>>> print(t[1:5]) # Prints the 2nd to 5th value in the tuple
(4, 6, 8, 10)
>>>
>>> print(t[1:]) # Prints the 2nd to the last value
(4, 6, 8, 10, 12, 14, 3.14)
>>>
—
Python Tutorials
Python Tutorial on this website can be found at:
https://www.testingdocs.com/python-tutorials/
More information on Python is available at the official website: