Set Example

Unit III: Data Structures in Python

Lists

Operations, Slicing, and Methods
  • Definition: Lists are data structures used to store multiple items in a single variable.

  • Characteristics:
      - Lists can contain mixed data types (heterogeneous).
      - They are mutable, meaning items can be changed after creation.

  • Slicing:
      - Extract subsets using slicing syntax, e.g., my_list[1:3] returns elements between indices 1 and 3 (exclusive).

  • Methods:
      - append(): Adds an item to the end of the list.
      - extend(): Extends the list by appending elements from another iterable.
      - remove(): Removes the first occurrence of a specified item.

Python Slicing Examples

In Python, you can extract elements as follows:

my_list = [1, 2, 3, 4, 5]
my_tuple = (6, 7, 8, 9, 10)
print(my_list[1:3])  # Output: [2, 3]
print(my_tuple[:3])  # Output: (6, 7, 8)
Memory Efficiency
  • Lists consist of two memory allocations:
      1. Fixed block: Contains Python object information.
      2. Variable-sized block: Allocated for the data elements.

  • Tuples are more memory efficient as they require a single contiguous block for storage.

Tuples

Creating and Printing
  • Definition: A tuple is an immutable collection suitable for storing multiple items.

  • Characteristics:
      - Represented with parentheses ().
      - Items are ordered and maintain their position as stored.
      - Can hold mixed data types.

Properties of Tuples
  • Immutability: Items cannot be reassigned after the tuple is created.

  • Advantages: More efficient for fixed data collections compared to lists.

Example of a Tuple
mytuple = ("apple", "banana", "cherry")
Tuple Methods
  • count(): Returns the number of times a specified value occurs in a tuple.

  • index(): Returns the position of the first occurrence of the specified value.

Sets

Overview
  • Definition: Sets are unordered collections that store multiple items without duplicates.

  • Characteristics:
      - Auto-removes duplicates.
      - Can only add immutable (hashable) items.
      - Introduced using curly braces {}.

  • Syntax Example: `thisset = {