📚

Understanding Tuples in Python

Oct 3, 2024

Introduction to Tuples

Overview

  • This lecture introduces tuples in Python.
  • Key topics include:
    • What is a tuple?
    • Tuple with one item
    • Length of a tuple
    • Tuple Constructor

What is a Tuple?

  • A tuple is a collection of items that are:
    • Indexed: Each item has an index (0, 1, 2, ...).
    • Ordered: The order of items remains the same.
    • Immutable: Once created, a tuple cannot be changed.

Syntax

  • Syntax to create a tuple: tuple_name = (item1, item2, item3, ...)
  • Tuples are defined using round brackets (parentheses), while lists use square brackets.

Example

  • Creating a tuple of cars: cars = ('Audi', 'Mercedes', 'BMW')
  • Accessing items by index:
    • cars[0] returns 'Audi'
    • cars[1] returns 'Mercedes'
    • cars[2] returns 'BMW'

Important Terms

  1. Indexed: Access items using their index.
  2. Immutable:
    • Attempting to change an item results in a TypeError.
    • Example: cars[0] = 'Ferrari'
  3. Ordered: The order of items is maintained.
  4. Duplicates: Tuples can have duplicate items.
    • Example: cars = ('Audi', 'Mercedes', 'Mercedes', 'BMW')

Tuple with One Item

  • To create a tuple with one item, a comma is mandatory.
  • Syntax: single_item_tuple = (item,)
  • Example without a comma results in a string instead of a tuple: car = ('Audi')

Length of a Tuple

  • Use the len() function to determine the length of a tuple.
  • Example: len(cars)
    • Returns the number of items in the tuple.

Tuple Constructor

  • An alternative way to create a tuple is using the tuple constructor: cars = tuple(('Audi', 'Mercedes', 'BMW'))
  • This also results in the tuple being created with the specified items.

Conclusion

  • The lecture covered the basics of tuples, including their properties, creation, and usage.
  • Further topics will be discussed in the next session.