Basic Python For ML December 12 ,2024

1. What is a Tuple?

A tuple is one of Python’s built-in data structures, used for storing a collection of items. While they share many similarities with lists, the defining characteristic of tuples is their immutability.

1.1 Definition

A tuple is:

  • An ordered collection of elements.
  • Immutable, meaning once it’s created, its elements cannot be modified, added, or removed.
  • Heterogeneous, allowing it to store different types of data like integers, strings, floats, and even other tuples.

Syntax: Tuples are defined using parentheses (), with elements separated by commas.

1.2 Example

# Examples of tuples
empty_tuple = ()                 # An empty tuple
single_element_tuple = (42,)     # A tuple with one element (comma is mandatory)
multi_type_tuple = (1, "Python", 3.14)  # A tuple with mixed data types
nested_tuple = (1, (2, 3), [4, 5])  # A tuple containing another tuple and a list

2. Key Features of Tuples

  1. Immutability
    Once created, the elements of a tuple cannot be changed.

    my_tuple = (10, 20, 30)
    my_tuple[1] = 25  # Error! Tuples are immutable
    
  2. Ordered Collection
    Elements are stored in a specific order, and their position can be accessed using an index.

    my_tuple = (10, 20, 30)
    print(my_tuple[0])  # Output: 10
    
  3. Allows Duplicates
    Like lists, tuples can have duplicate elements.

    my_tuple = (1, 2, 2, 3)
    print(my_tuple)  # Output: (1, 2, 2, 3)
    
  4. Hashable (if all elements are immutable)
    Tuples can be used as dictionary keys if all their elements are immutable.

    my_dict = {(1, 2): "value"}
    print(my_dict[(1, 2)])  # Output: value
    

3. Why Choose Tuples?

Tuples are preferred over lists in certain scenarios due to their unique properties:

3.1 Performance

Tuples are faster than lists, making them a better choice when working with fixed, unchanging datasets.

3.2 Memory Efficiency

Tuples use less memory than lists, as Python doesn’t need to store extra information to manage mutability.

3.3 Immutability for Safety

When you want to ensure that data remains unchanged throughout your program, tuples provide a reliable solution.

Example Use Case: Storing configuration data:

config = ("localhost", 5432, "admin")

4. Creating Tuples

4.1 Syntax

Tuples are created using parentheses () or the tuple() constructor.

Examples:

# Using parentheses
my_tuple = (1, 2, 3)

# Using the tuple() function
my_tuple = tuple([1, 2, 3])  # Converts a list to a tuple

4.2 Special Case: Single-element Tuples

To define a tuple with one element, include a trailing comma , to distinguish it from a simple value.

Example:

single_value = (42)      # Not a tuple, just an integer
single_tuple = (42,)     # This is a tuple

5. Accessing Tuple Elements

5.1 Indexing

Tuples use zero-based indexing to access elements.

Example:

my_tuple = (10, 20, 30)
print(my_tuple[0])  # Output: 10
print(my_tuple[-1])  # Output: 30 (negative indexing)

5.2 Slicing

You can retrieve a range of elements using slicing: tuple[start:end:step].

Example:

my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4])  # Output: (2, 3, 4)
print(my_tuple[::-1])  # Output: (5, 4, 3, 2, 1) (reversed tuple)

6. Operations on Tuples

6.1 Concatenation

Combine two or more tuples using the + operator.

tuple1 = (1, 2)
tuple2 = (3, 4)
result = tuple1 + tuple2
print(result)  # Output: (1, 2, 3, 4)

6.2 Repetition

Repeat a tuple multiple times using the * operator.

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

6.3 Membership Test

Check if an element exists in a tuple using the in keyword.

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

7. Advanced Features

7.1 Tuple Methods

  • count(): Returns the number of times an element appears in the tuple.

    my_tuple = (1, 2, 2, 3)
    print(my_tuple.count(2))  # Output: 2
    
  • index(): Returns the index of the first occurrence of a specified element.

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

7.2 Tuple Unpacking

Assign tuple elements to individual variables in a single step.

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

7.3 Nested Tuples

Tuples can contain other tuples as elements.

nested_tuple = (1, (2, 3), (4, (5, 6)))
print(nested_tuple[2][1][1])  # Output: 6

8. Tuples vs. Lists

FeatureTupleList
MutabilityImmutableMutable
Syntax(element1, element2)[element1, element2]
PerformanceFaster for read-only dataSlower for modifications
Memory UsageLessMore
Use CaseFixed collectionsDynamic collections

9. Real-life Applications of Tuples

  1. Coordinates:
    Store geographical or 3D coordinates.

    location = (40.7128, -74.0060)
    
  2. Database Records:
    Represent rows in a database where fields should remain unchanged.
  3. Returning Multiple Values from Functions:

    def get_stats():
        return (mean, median, mode)
    stats = get_stats()
    
  4. Dictionary Keys:
    Use tuples as keys for multi-dimensional data.

    distances = {(0, 0): "origin", (1, 2): "point"}
    

 

Next Topic : Sets in Python

 

Purnima
0

You must logged in to post comments.

Get In Touch

123 Street, New York, USA

+012 345 67890

techiefreak87@gmail.com

© Design & Developed by HW Infotech