0% found this document useful (0 votes)
0 views3 pages

Python Tuple Methods Example

Uploaded by

hasanhiba442
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views3 pages

Python Tuple Methods Example

Uploaded by

hasanhiba442
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Python Tuple Methods Example

Python Tuple Methods and Functions

Tuples are immutable sequences in Python, and unlike lists, they do not support methods that alter

their contents, such as append or remove. However, there are some common methods that can be

used with tuples, as well as other tuple-specific functions.

Common Functions with Lists and Tuples:

1. len(tuple) - Returns the number of items in the tuple.

Example:

tuple_example = (1, 2, 3, 4, 5)

print("Length of the tuple:", len(tuple_example))

2. count(item) - Returns the number of occurrences of an item in the tuple.

Example:

count_of_3 = tuple_example.count(3)

print("Count of 3:", count_of_3)

3. index(item) - Returns the index of the first occurrence of an item in the tuple.

Example:

index_of_4 = tuple_example.index(4)

print("Index of 4:", index_of_4)

Non-Common Methods and Functions for Tuples:


1. max(tuple) - Returns the largest item in the tuple.

Example:

tuple_example = (1, 5, 3, 9, 2)

max_item = max(tuple_example)

print("Max item:", max_item)

2. min(tuple) - Returns the smallest item in the tuple.

Example:

tuple_example = (1, 5, 3, 9, 2)

min_item = min(tuple_example)

print("Min item:", min_item)

3. tuple(iterable) - Converts an iterable (like a list) into a tuple.

Example:

list_example = [10, 20, 30]

tuple_from_list = tuple(list_example)

print("Tuple from list:", tuple_from_list)

4. reversed(tuple) - Returns an iterator that accesses the given tuple in the reverse order.

Example:

tuple_example = (1, 2, 3, 4)

reversed_tuple = tuple(reversed(tuple_example))

print("Reversed tuple:", reversed_tuple)

5. sorted(tuple) - Returns a sorted list from the items in the tuple.

Example:
tuple_example = (3, 1, 4, 2)

sorted_tuple = sorted(tuple_example)

print("Sorted tuple:", sorted_tuple)

Note: Since tuples are immutable, methods like append, remove, pop, insert, and extend do not

exist for tuples.

You might also like