Tuples and Sets

Tuples in Python are immutable sequences used to store collections of items.

Key Characteristics

  • Immutable: Once a tuple is created, its elements cannot be changed, added, or removed.
  • Ordered: Elements are stored in a specific order, and you can access them by index.
  • Heterogeneous: Tuples can store elements of different data types (e.g., integers, strings, lists).

Creating Tuples in Python

A tuple in Python is a finite ordered list of values that can be of different types. Tuples are used to group related data together without needing to create a custom data structure.

Syntax for Creating Tuples

A tuple is defined by placing a comma-separated list of values inside parentheses. Each value within a tuple is referred to as an item.

tuple_name = (item_1, item_2, item_3, ..., item_n)

Example:

tuple.py
# Creating a tuple with a mix of strings and numbers
internet = ("cern", "tech", "www", 2024)
print(internet)           # Output: ('cern', 'tech', 'www', 2024)
print(type(internet))     # Output: <class 'tuple'>

Tuple Creation Without Parentheses

You can also create a tuple without using parentheses, relying on commas to separate the items. However, parentheses are commonly used to enhance readability.

f1 = "ferrari", "redbull", "mercedes", "williams", "renault"
print(f1)                 # Output: ('ferrari', 'redbull', 'mercedes', 'williams', 'renault')
print(type(f1))           # Output: <class 'tuple'>

Creating Empty Tuples

An empty tuple can be created by simply using an empty pair of parentheses.

empty_tuple = ()
print(empty_tuple)        # Output: ()
print(type(empty_tuple))  # Output: <class 'tuple'>

Nested Tuples

Tuples can store other tuples as items, allowing for the creation of complex, nested data structures. Tuples can hold different types of items, making them versatile.

air_force = ("f15", "f22a", "f35a")
fighter_jets = (1988, 2005, 2016, air_force)
print(fighter_jets)       # Output: (1988, 2005, 2016, ('f15', 'f22a', 'f35a'))
print(type(fighter_jets)) # Output: <class 'tuple'>

Special Cases: Single and Empty Tuples

Creating a tuple with a single item requires a trailing comma to differentiate it from a regular value in parentheses.

# Empty tuple
empty = ()
print(type(empty))        # Output: <class 'tuple'>
 
# Singleton tuple (tuple with one item)
singleton = 'hello',
print(singleton)          # Output: ('hello',)
print(type(singleton))    # Output: <class 'tuple'>

Basic Tuple Operations in Python

Tuples in Python support various operations similar to lists. Below are some of the key operations you can perform on tuples:

  • Concatenation (+ Operator) - You can concatenate two or more tuples using the + operator. This operation creates a new tuple by combining the items from the given tuples.

    Example:

    tuple_1 = (2, 0, 1, 4)
    tuple_2 = (2, 0, 1, 9)
    result = tuple_1 + tuple_2
    print(result)  # Output: (2, 0, 1, 4, 2, 0, 1, 9)
  • Repetition (* Operator) - The * operator allows you to repeat the items of a tuple a specified number of times, resulting in a new tuple.

    Example:

    tuple_1 = (2, 0, 1, 4)
    result = tuple_1 * 3
    print(result)  # Output: (2, 0, 1, 4, 2, 0, 1, 4, 2, 0, 1, 4)
  • Comparison (==, !=, <, >, <=, >= Operators) - Tuples can be compared using comparison operators. The comparison is done element by element, starting from the first element.

    Example:

    tuple_1 = (9, 8, 7)
    tuple_2 = (9, 1, 1)
    print(tuple_1 > tuple_2)   # Output: True
    print(tuple_1 != tuple_2)  # Output: True
  • Membership Testing (in, not in Operators) - You can check whether an item exists in a tuple using the in or not in operators. The result is a Boolean value: True if the item is present, otherwise False.

    Example:

    tuple_items = (1, 9, 8, 8)
    print(1 in tuple_items)    # Output: True
    print(25 in tuple_items)   # Output: False
  • The tuple() Function - The tuple() function is a built-in function that can be used to create a tuple from a sequence, such as a string, list, or another tuple. If no argument is provided, it creates an empty tuple.

    Examples:

    • Converting a String to a Tuple

      site = "hptu"
      string_to_tuple = tuple(site)
      print(string_to_tuple)  # Output: ('h', 'p', 't', 'u')
    • Converting a List to a Tuple

      zeus = ["g", "o", "d", "o", "f", "s", "k", "y"]
      list_to_tuple = tuple(zeus)
      print(list_to_tuple)  # Output: ('g', 'o', 'd', 'o', 'f', 's', 'k', 'y')
    • Nesting Tuples

      You can create a tuple of tuples, allowing for complex nested structures.

      letters = ("a", "b", "c")
      numbers = (1, 2, 3)
      nested_tuples = (letters, numbers)
      print(nested_tuples)  # Output: (('a', 'b', 'c'), (1, 2, 3))

      Note: When concatenating tuples, the types must be compatible. For example, you cannot directly concatenate a tuple with a string or list; you must first convert them to a tuple using the tuple() function.

      Examples of Incorrect Concatenation

      • Concatenating Tuple and String

        site = "hptu"
        string_to_tuple = tuple(site)
        string_to_tuple + "exam helper"
        # Error: TypeError: can only concatenate tuple (not "str") to tuple
      • Concatenating Tuple and List

        zeus = ["g", "o", "d", "o", "f", "s", "k", "y"]
        list_to_tuple = tuple(zeus)
        list_to_tuple + ["g", "r", "e", "e", "k"]
        # Error: TypeError: can only concatenate tuple (not "list") to tuple

Indexing and Slicing in Tuples

Tuples in Python allow you to access individual elements and extract parts of the tuple using indexing and slicing techniques. These operations are crucial for working with tuple data efficiently.

Indexing in Tuples

Indexing is used to access individual elements in a tuple. Each element in a tuple is associated with an index number, starting from 0 for the first item. You can also use negative indexing to access elements from the end of the tuple, with -1 being the last item.

Syntax:

tuple_name[index]
  • Positive Indexing: The index starts at 0 for the first element, 1 for the second, and so on.

    Example:

    holy_places = ("jerusalem", "kashivishwanath", "harmandirsahib", "bethlehem", "mahabodhi")
    print(holy_places[0])  # Output: 'jerusalem'
    print(holy_places[3])  # Output: 'bethlehem'
  • Negative Indexing: Negative indexes start at -1 for the last element, -2 for the second last, and so on.

    Example:

    holy_places = ("jerusalem", "kashivishwanath", "harmandirsahib", "bethlehem", "mahabodhi")
    print(holy_places[-1])  # Output: 'mahabodhi'
    print(holy_places[-2])  # Output: 'bethlehem'

Note: Accessing an index that is out of range will raise an IndexError.

Example of an Out-of-Range Index:

holy_places = ("jerusalem", "kashivishwanath", "harmandirsahib", "bethlehem", "mahabodhi")
print(holy_places[6])
# Output: IndexError: tuple index out of range

Slicing in Tuples

Slicing allows you to extract a part of the tuple by specifying a range of index values. The syntax for slicing is:

Syntax:

tuple_name[start:stop:step]
  • start: The index to begin slicing (inclusive).

  • stop: The index to end slicing (exclusive).

  • step: The interval between each index (optional).

  • Basic Slicing: You can slice a tuple from one index to another.

    Example:

    colors = ("v", "i", "b", "g", "y", "o", "r")
    print(colors[1:4])  # Output: ('i', 'b', 'g')
  • Omitting Start or Stop: You can omit the start or stop index to slice from the beginning or up to the end of the tuple, respectively.

    Examples:

    colors = ("v", "i", "b", "g", "y", "o", "r")
    print(colors[:5])   # Output: ('v', 'i', 'b', 'g', 'y')
    print(colors[3:])   # Output: ('g', 'y', 'o', 'r')
  • Slicing with Step: The step parameter in slicing allows you to specify the interval between elements in the slice. By default, the step is 1, meaning every element in the specified range is included. You can change the step to select elements at different intervals.

    Example:

    colors = ("v", "i", "b", "g", "y", "o", "r")
    print(colors[::2])  # Output: ('v', 'b', 'y', 'r')
    print(colors[1:5:2])  # Output: ('i', 'g')
    • In the first print(colors[::2]), the step is 2, so the slice starts from the first element ('v') and includes every second element, resulting in ('v', 'b', 'y', 'r').

    • In the second print(colors[1:5:2]), the slice starts at index 1 ('i') and ends at index 5 (not including index 5). The step is 2, so it selects every second element within the specified range. The elements at index 1 ('i') and index 3 ('g') are included, resulting in ('i', 'g').

  • Reversing a Tuple: You can reverse the elements in a tuple by using a negative step value.

    Example:

    colors = ("v", "i", "b", "g", "y", "o", "r")
    print(colors[::-1])  # Output: ('r', 'o', 'y', 'g', 'b', 'i', 'v')
  • Negative Indexing in Slicing: You can also use negative indexing in slicing to work from the end of the tuple.

    Example:

    colors = ("v", "i", "b", "g", "y", "o", "r")
    print(colors[-5:-2])  # Output: ('b', 'g', 'y')

Built-In Functions Used on Tuples

Python provides several built-in functions that can be used to perform operations on tuples. These functions make it easier to work with tuple data by offering utilities like counting elements, summing numerical values, and sorting.

Common Built-In Functions for Tuples

Built-In FunctionDescription
len()Returns the number of items in a tuple.
sum()Returns the sum of numbers in the tuple.
sorted()Returns a sorted copy of the tuple as a list, without modifying the original tuple.

Examples:

  1. Using len() to Count Items in a Tuple

    The len() function returns the number of elements in a tuple.

    years = (1987, 1985, 1981, 1996)
    print(len(years))  # Output: 4
    • Explanation: The len() function is used here to determine that the tuple years contains 4 items.
  2. Using sum() to Add Up Numbers in a Tuple

    The sum() function calculates the total sum of all numerical elements in a tuple.

    years = (1987, 1985, 1981, 1996)
    print(sum(years))  # Output: 7949
    • Explanation: The sum() function adds up all the years in the tuple, giving a total of 7949.
  3. Using sorted() to Sort Tuple Elements

    The sorted() function returns a sorted list of the tuple's elements, leaving the original tuple unchanged.

    years = (1987, 1985, 1981, 1996)
    sorted_years = sorted(years)
    print(sorted_years)  # Output: [1981, 1985, 1987, 1996]
    • Explanation: The sorted() function generates a new sorted list [1981, 1985, 1987, 1996] from the tuple years. The original tuple remains unaltered.

    • When using sorted() on tuples containing strings, the sorting is based on the ASCII values of the characters.

      Example:

      names = ("eniv", "vine", "justin")
      sorted_names = sorted(names)
      print(sorted_names)  # Output: ['eniv', 'justin', 'vine']

Relation Between Tuples and Lists

Tuples and lists in Python are both sequence types that store collections of items. Despite their similarities, they serve different purposes and have distinct characteristics that make them suitable for different scenarios.

Key Difference

  • Tuples are immutable, meaning that once a tuple is created, its elements cannot be changed, added, or removed. This immutability makes tuples a good choice for fixed collections of items where data integrity is crucial.
  • Lists are mutable, allowing for modifications after creation. Items in a list can be added, removed, or changed, making lists more flexible for dynamic collections of items.

Examples:

  1. Immutability of Tuples:

    Attempting to modify an element of a tuple results in an error:

    coral_reef = ("great_barrier", "ningaloo_coast", "amazon_reef", "pickles_reef")
    coral_reef[0] = "pickles_reef"  # This will raise a TypeError
    • Explanation: Since tuples are immutable, trying to assign a new value to an element in the coral_reef tuple results in a TypeError.
  2. Converting a Tuple to a List:

    You can convert a tuple to a list to make it mutable:

    coral_reef = ("great_barrier", "ningaloo_coast", "amazon_reef", "pickles_reef")
    coral_reef_list = list(coral_reef)
    print(coral_reef_list)
    # Output: ['great_barrier', 'ningaloo_coast', 'amazon_reef', 'pickles_reef']
    • Explanation: The tuple coral_reef is converted into a list using the list() function, allowing modifications to the new list.
  3. Mutability of Elements Within a Tuple:

    If a tuple contains a mutable item, such as a list, changes to that item are reflected in the tuple:

    german_cars = ["porsche", "audi", "bmw"]
    european_cars = ("ferrari", "volvo", "renault", german_cars)
    european_cars[3].append("mercedes")
    print(german_cars)
    # Output: ['porsche', 'audi', 'bmw', 'mercedes']
    print(european_cars)
    # Output: ('ferrari', 'volvo', 'renault', ['porsche', 'audi', 'bmw', 'mercedes'])
    • Explanation: While the european_cars tuple itself remains immutable, the list within it (german_cars) can be modified. The change is reflected in both the original list and the tuple because they reference the same list object.

Relation Between Tuples and Dictionaries

Tuples and dictionaries are both versatile data structures in Python, but they serve different purposes and have unique characteristics. Tuples can be used effectively in conjunction with dictionaries in a few specific ways:

Tuples as Dictionary Keys and Values:

  1. Using Tuples to Build Dictionaries:

    Tuples can be utilized to create dictionaries, where each tuple represents a key-value pair. To achieve this, each tuple must contain exactly two elements: the first element is used as the key and the second as the value.

    Example:

    fish_weight_kg = (("white_shark", 520), ("beluga", 1571), ("greenland_shark", 1400))
    fish_weight_kg_dict = dict(fish_weight_kg)
    print(fish_weight_kg_dict)
    # Output: {'white_shark': 520, 'beluga': 1571, 'greenland_shark': 1400}
    • Explanation: In this example, fish_weight_kg is a tuple of tuples. Each inner tuple has two elements where the first is the key and the second is the value. The dict() function converts this tuple of tuples into a dictionary.
  2. Converting Dictionaries to Tuples:

    The items() method of a dictionary returns a view object that displays a list of tuples. Each tuple contains a key-value pair from the dictionary.

    Example:

    founding_year = {"Google": 1996, "Apple": 1976, "Sony": 1946, "ebay": 1995, "IBM": 1911}
    for company, year in founding_year.items():
        print(f"{company} was found in the year {year}")

    Output:

    Google was found in the year 1996
    Apple was found in the year 1976
    Sony was found in the year 1946
    ebay was found in the year 1995
    IBM was found in the year 1911
    • Explanation: The items() method returns a view of the dictionary's key-value pairs as tuples, which can be iterated over in a loop to access both keys and values.
How's article quality?

Last updated on -

Page Contents