python data structures

Data structures are broadly categorized into two main types:

  1. Simple Data Structures: These are fundamental, built-in data types.

    • Examples: integers, floats, characters, and booleans.

  2. Compound Data Structures: These are more complex structures built from combinations of simple data structures.

    • Examples: lists, tuples, sets, and dictionaries.

Compound data structures can be further classified based on how their elements are organized:

Linear Data Structures

Elements are arranged in a sequential manner.

  • Examples: arrays, **lists, stacks, and queues.

Non-Linear Data Structures

Elements are arranged in a hierarchical or interconnected manner.

  • Examples: trees and graphs.

Python List

A list is a compound, linear data structure in Python.

  • Mutable: Values inside a list can be changed, added, or removed at any time.

  • Can store an unlimited number of values of different data types.

  • Accessing data: Elements can be accessed using indexing (e.g., mylist[0]mylist[0]) and slicing (e.g., mylist[1:3]mylist[1:3]).

Stack

A stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle. This means the last item added is the first one to be removed.

  • LIFO (Last-In, First-Out):

    • Imagine a stack of plates: You add new plates to the top, and when you take a plate, you take it from the top (the last one put on).

    • Example: To take out a book from a stack of 5-6 books, you must first remove the books on top of it.

  • Key Operations:

    • Push: Adds an item to the top of the stack.

    • Pop: Removes the most recently added item (the top item) from the stack.

Underflow (Stack)

Occurs when an attempt is made to remove an item from an empty stack.

  • Scenario: Imagine a stack of plates is empty.

  • Action: You try to remove a plate.

  • Result: This action leads to an underflow error.

Overflow (Stack)

Occurs when an attempt is made to add an item to a full stack.

  • Scenario: Imagine a stack of plates is already full (has reached its maximum capacity).

  • Action: You try to add another plate.

  • Result: This action leads to an overflow error.