Loading...
Loading...
00:00:00

Tuple In Python

A tuple in Python is an immutable, ordered collection of items, which can be of any data type, including numbers, strings, and other objects. Tuples are defined using parentheses () and items are separated by commas.

fruits = ('apple', 'banana', 'cherry')
numbers = (1, 2, 3, 4, 5)

Because tuples are immutable, once they are created, you cannot add, remove, or modify items. However, you can access items in a tuple by using an index, which starts at 0 for the first item and increases by 1 for each subsequent item:

print(fruits[0])  # 'apple'
print(fruits[1])  # 'banana'

You can also use negative indexing to access items from the end of the tuple:

print(fruits[-1])  # 'cherry'
print(fruits[-2])  # 'banana'

Tuples support various operations, such as concatenation, repetition, and slicing. You can also use various built-in functions and methods to work with tuples, such as len(), min(), max(), and sorted().

One of the main differences between lists and tuples is that tuples are more memory-efficient than lists, since they are immutable. Tuples are also often used for multiple return values from a function, for example:

def divide(x, y):
    return x // y, x % y

result = divide(10, 3)
print(result)  # (3, 1)

In this example, the divide() function returns a tuple with two values, the quotient and the remainder. The tuple can then be unpacked into separate variables, if needed.

In Python 3, tuples are a built-in data type that support several methods. Here's a list of the most common methods that can be used with tuples:

  1. count(): Returns the number of times a specified value appears in the tuple.
  2. index(): Returns the index of the first occurrence of a specified value in the tuple.
  3. len(): Returns the length (number of items) in the tuple.
  4. max(): Returns the largest item in the tuple.
  5. min(): Returns the smallest item in the tuple.
  6. sorted(): Returns a new sorted list from elements in the tuple.
  7. tuple(): Converts an iterable object (such as a list) into a tuple.

It's important to note that tuples are immutable, meaning their elements cannot be modified once they are created. This makes them suitable for use as keys in dictionaries, or as elements in sets.

Tuple() Constructor

Create a new tuple using tuple() constructor. it takes one arguments

a = tuple([10,29,93,-82,2,87])
print(a)    # (10, 29, 93, -82, 2, 87)

Accessing Tuple

we can access tuple similar to list using index . index always startswith 0 .

a = tuple([10,29,93,-82,2,87])
print(a[0])    # 10
print(a[1])    # 20
print(a[2])    # 93

Tuple Count() Method

count the item in tuple with specified value

a = tuple([10,2,93,-82,2,87])
print(a.count(2))    # 2
print(a.count(20))   # 0

Tuple Index() Method

find the index of specified value it return the first occurance. If value is not found raise error "x is not found" .

a = tuple([10,2,93,-82,2,87])
print(a.index(2))    # 1