Pages

Aug 24, 2026

Python Data Structures and Type

 1. Dictionary (The Hash Table)

  • Definition: An unordered collection of key-value pairs.

  • Internal Working: Uses a Hash Table. Python passes the key through a hash function to get an index. If two keys hash to the same index (Collision), Python uses Open Addressing (specifically pseudo-random probing) to find the next slot.

  • Purpose: Fast lookups and mapping.

  • Best/Avg Case: $O(1)$ for insertion, deletion, and lookup.

  • Worst Case: $O(n)$ if hash collisions are excessive.

2. List (The Dynamic Array) : numbers = [10, 20, 30, 40, 50]

  • Definition: A mutable, ordered sequence of elements.

  • Internal Working: Implemented as an array of pointers to objects. It "over-allocates" memory to ensure that appending is usually $O(1)$. When full, it allocates a new, larger block of memory and copies elements ($O(n)$).

  • List Slicing : list[start:stop:step] - print(numbers[1:4])

  • append() : numbers.append(40) , a.append([3, 4]) - numbers = [1, 2, [3, 4]]

  • insert() : numbers.insert(1, 15) 

  • extend() : numbers.extend([30, 40, 50]) 

  • remove() : numbers.remove(20)

  • pop() :  x = numbers.pop()

  • del : del numbers[1]

  • index : numbers.index(30)

  • sort() vs sorted() : new_numbers = sorted(numbers) and numbers.sort()
    sort() modifies the original list
    sorted() creates a new list

3. Tuples - immutable collection of objects ()

4. Set - A set stores unique elements

5. Integer  - 0, 1, 2, 3, 4 etc

6. String - "adhiashdas"

7. Float - 1.1, 3.0, 4.0

8. Queue - FIFO — First In, First Out

from collections import deque

queue = deque()

queue.append(10)

queue.append(20)

queue.append(30)

print(queue.popleft())

9. deque - deque means double-ended queue.
from collections import deque

d = deque([10, 20, 30])

d.append(40)

d.appendleft(5)

print(d)


No comments:

Post a Comment