📚

Overview of Python Data Collections

May 7, 2025

Lecture Notes: Python Collections

General Purpose Collections

  • Four main types: Lists, Sets, Tuples, and (later) Dictionaries.
  • Purpose: Collections act as a single variable that stores multiple values.

Lists

  • Syntax: Values enclosed in square brackets [].
  • Characteristics:
    • Ordered and changeable.
    • Allows duplicates.
  • Accessing Elements:
    • Use index operator, e.g., fruits[0] for the first element.
    • Supports slicing, e.g., fruits[0:3].
    • Indexes start at 0.
  • Iterating: Use a for loop, e.g., for fruit in fruits:.
  • Common Methods:
    • append(): Adds element at the end.
    • remove(): Removes first occurrence of a value.
    • insert(index, element): Inserts an element at a specified index.
    • sort(): Sorts the list.
    • reverse(): Reverses the order of the list.
    • clear(): Removes all elements.
    • count(value): Counts occurrences of a value.
    • index(value): Returns index of the first occurrence.
  • Length: Use len(list).
  • Checking Membership: Use in operator, e.g., 'apple' in fruits.

Sets

  • Syntax: Values enclosed in curly braces {}.
  • Characteristics:
    • Unordered and immutable (elements can't be changed).
    • No duplicates allowed.
  • Modifying:
    • add(element): Adds an element.
    • remove(element): Removes a specific element.
    • pop(): Removes a random element.
    • clear(): Removes all elements.
  • Accessing Elements:
    • Cannot use indexing.
  • Checking Membership: Use in operator.
  • Length: Use len(set).

Tuples

  • Syntax: Values enclosed in parentheses ().
  • Characteristics:
    • Ordered and unchangeable.
    • Allows duplicates.
    • Faster than lists.
  • Accessing Elements:
    • Can use indexing, e.g., fruits[0].
  • Common Methods:
    • count(value): Counts occurrences of a value.
    • index(value): Returns index of the first occurrence.
  • Length: Use len(tuple).
  • Checking Membership: Use in operator.

Summary

  • Lists: Ordered, changeable, allows duplicates.
  • Sets: Unordered, immutable but can add/remove elements, no duplicates.
  • Tuples: Ordered, unchangeable, allows duplicates, faster than lists.
  • General: Collections are like single variables for multiple values.