Python Tuples
In Python, a tuple is a data structure that stores an ordered collection of items. Unlike a list, a tuple is immutable, which means that the items in a tuple cannot be modified. In Python, tuples are represented by round brackets () and the items in a tuple are separated by commas.
Creating a Tuple
To create a tuple in Python, use round brackets () and separate the items in the tuple with commas. Here are some examples of creating tuples in Python:
As you can see, a tuple can store items of any data type, including other tuples.
Accessing and Modifying Tuple Items
In Python, you can access the items in a tuple using indexing. To access an item in a tuple, use the square bracket notation [] and specify the index of the item you want to access. In Python, the index of the first item in a tuple is 0, and the index of the last item in a tuple is -1. Here are some examples of accessing items in a tuple:
As you can see, you can access the items in a tuple using indexing, just like you would with a list. However, unlike a list, you cannot modify the items in an existing tuple, because tuples are immutable. If you try to modify a tuple, you will get a TypeError. For example:
In contr…
No comments yet. Add the first comment to start the discussion.