Advance Python - II
Tuples in Python
A Python Tuple is a collection of objects separated by commas. In many ways, a tuple is similar to a list: it supports indexing, can hold nested objects, and allows repetition of elements.
However, tuples are immutable—meaning once created, their contents cannot be changed—unlike lists, which are mutable.
Creating Python Tuples
To create a tuple, we enclose the elements in parentheses ( ).
Example:
Output:
Accessing Values in Python Tuples
There are two ways to access values in a tuple: using positive indices or negative indices.
Method 1: Using Positive Index
Use square brackets [ ] and positive indices (starting from 0) to access items:
Output:
Method 2: Using Negative Index
Negative indices allow you to access elements from the end of the tuple backward:
Output:
Slicing Python Tuples
Like strings and lists, tuples support slicing to extract a range of elements.
Output:
Finding Length of a Tuple
Use the len() function to get the number of elements in a tuple.
Output: