Home » Data Science » Python » Python Tuples

Newly Updated Posts

Python Tuples

In this tutorial we wil learn tuples in Python:

Tuples are ordered, immutable sequences in Python. They are similar to lists but have some key differences. Here are some important points about tuples

  1. Creation : Tuples are created by enclosing comma-separated values in parentheses. For example:
my_tuple = (1, 2, 3)
empty_tuple = ()
single_value_tuple = (4,)

2. Accessing Elements : Individual elements of a tuple can be accessed using indexing, similar to lists. The indexing starts at 0. For example:

my_tuple = (1, 2, 3)
print(my_tuple[0])  # Output: 1

3. Immutable Nature:Tuples are immutable, meaning their elements cannot be changed after creation. However, if a tuple contains mutable objects (like lists), those objects can be modified. But you cannot reassign or modify the elements of a tuple directly.

4. Length and Membership: The len() function can be used to get the length of a tuple, and the in keyword can be used to check if an element is present in a tuple.

my_tuple = (1, 2, 3)
print(len(my_tuple))  # Output: 3

if 2 in my_tuple:
    print("2 is present in the tuple.")

5. Tuple Concatenation and Repetition: Tuples can be concatenated using the + operator, and repetition can be achieved using the * operator.

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple)  # Output: (1, 2, 3, 4, 5, 6)

repeated_tuple = tuple1 * 3
print(repeated_tuple)  # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)

6. Tuple Unpacking: Tuples can be unpacked into individual variables. The number of variables must match the number of elements in the tuple.

my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a)  # Output: 1
print(b)  # Output: 2
print(c)  # Output: 3

7. Returning Multiple Values: Tuples are commonly used to return multiple values from a function.

def get_name_and_age():
    name = "Alice"
    age = 25
    return name, age

name, age = get_name_and_age()
print(name)  # Output: Alice
print(age)   # Output: 25

Tuples are useful when you want to store a collection of items that should not be modified. They provide a lightweight alternative to lists in scenarios where immutability is desired.