Code Project

Link Unit

Monday, February 10, 2025

List and Tuple - Difference

 The key difference between lists and tuples in Python is their mutability:

  • List: Ordered and mutable, meaning you can change its elements (add, remove, or modify them).
  • Tuple: Ordered but immutable, meaning once it's created, its elements cannot be changed.

Example: List

# Creating a list
my_list = [1, 2, 3] # Modifying the list my_list[0] = 10 # Update an element my_list.append(4) # Add a new element my_list.remove(2) # Remove an element print(my_list) # Output: [10, 3, 4]

Example: Tuple

# Creating a tuple
my_tuple = (1, 2, 3) # Trying to modify the tuple # my_tuple[0] = 10 # This will raise an error: TypeError: 'tuple' object does not support item assignment # Accessing elements (this is allowed) print(my_tuple[0]) # Output: 1

Key Characteristics:

  1. Mutability:

    • Lists allow you to modify their elements.
    • Tuples do not allow modification after creation.
  2. Performance:

    • Tuples are slightly faster than lists due to their immutability.
  3. Usage:

    • Use lists when the data needs to change (e.g., dynamically adding/removing elements).
    • Use tuples for fixed collections of data (e.g., coordinates (x, y) or configuration data).

Practical Difference Example:

List Use Case:

# Shopping list: It changes over time
shopping_list = ["milk", "bread"] shopping_list.append("eggs") print(shopping_list) # Output: ['milk', 'bread', 'eggs']

Tuple Use Case:

# Days of the week: Fixed and unchanging
days_of_week = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") print(days_of_week) # Output: ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')

No comments: