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:

animals = ("Lion", "Tiger", "Leopard") print(animals)

Output:

('Lion', 'Tiger', 'Leopard')

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:

languages = ("Python", "JavaScript", "Rust") print("Value in languages[0] =", languages[0]) print("Value in languages[1] =", languages[1]) print("Value in languages[2] =", languages[2])

Output:

Value in languages[0] = Python Value in languages[1] = JavaScript Value in languages[2] = Rust

Method 2: Using Negative Index

Negative indices allow you to access elements from the end of the tuple backward:

colors = ("Red", "Green", "Blue") print("Value in colors[-3] =", colors[-3]) print("Value in colors[-2] =", colors[-2]) print("Value in colors[-1] =", colors[-1])

Output:

Value in colors[-3] = Red Value in colors[-2] = Green Value in colors[-1] = Blue

Slicing Python Tuples

Like strings and lists, tuples support slicing to extract a range of elements.

numbers = (10, 20, 30, 40, 50) print(numbers[2:]) print(numbers[::-1]) print(numbers[1:4])

Output:

(30, 40, 50) (50, 40, 30, 20, 10) (20, 30, 40)

Finding Length of a Tuple

Use the len() function to get the number of elements in a tuple.

tuple_data = ("apple", "banana", "cherry") print(len(tuple_data))

Output:

3

Popular Posts