Data structure in python

 


Here is a simple and clear explanation of Data Structures in Python, perfect for beginners:


Data Structures in Python (Explained Simply)

Data structures are ways of storing and organizing data so that they can be used efficiently.

Python has 4 built-in (core) data structures:


1. List

  • Ordered
  • Mutable (you can change values)
  • Allows duplicate values

Example

fruits = ["apple", "banana", "mango"]
print(fruits[1])     # banana
fruits.append("orange")

2. Tuple

  • Ordered
  • Immutable (cannot change values after creation)
  • Faster than lists
  • Allows duplicates

Example

colors = ("red", "green", "blue")
print(colors[0])   # red

3. Set

  • Unordered
  • Mutable
  • No duplicate values
  • Used for operations like union, intersection

Example

numbers = {1, 2, 3, 3, 4}
print(numbers)   # {1, 2, 3, 4}

4. Dictionary (dict)

  • Key–value pairs
  • Mutable
  • Keys must be unique
  • Very fast for search

Example

student = {
    "name": "Meenu",
    "age": 21,
    "course": "Python"
}
print(student["name"])  # Meenu

Summary Table

Data Structure Ordered Mutable Allows Duplicates Example Use
List Yes Yes Yes Store items in sequence
Tuple Yes No Yes Fixed data (e.g., coordinates)
Set No Yes No Remove duplicates, math operations
Dictionary No (in concept) Yes Keys: No, Values: Yes Store data with keys

When to Use What?

  • List → When you need an ordered, changeable collection
  • Tuple → When data should NOT change (e.g., constants)
  • Set → When you want unique items
  • Dictionary → When you need key-value mapping (fast access)

Here is a very detailed, complete, and beginner-friendly explanation of Data Structures in Python — covering built-in, advanced, custom, time complexities, use cases, and diagrams.


🧠 Data Structures in Python (Very Detailed Notes)

Python data structures are divided into:

A. Built-in Data Structures

  1. List
  2. Tuple
  3. Set
  4. Dictionary

🟩 1. LIST

A list is an ordered, mutable collection that can store mixed data types.

✔ Features

  • Ordered (index-based)
  • Mutable
  • Allows duplicates
  • Supports slicing
  • Dynamic size

✔ Syntax

my_list = [10, 20, 30, "hello", 30.5]

✔ Accessing Elements

print(my_list[0])
print(my_list[-1])

✔ List Methods (Important)

Method Description
append() Add element at end
insert() Add at a specific index
extend() Add multiple items
remove() Remove first matching item
pop() Remove by index
sort() Sort the list
reverse() Reverse the list

✔ Example

nums = [3, 1, 5, 7]
nums.append(10)
nums.sort()

✔ Time Complexity (Important)

Operation Complexity
Indexing O(1)
Insert O(n)
Delete O(n)
Append O(1)
Search O(n)

🟧 2. TUPLE

A tuple is an ordered, immutable collection.

✔ Features

  • Ordered
  • Immutable (values cannot change)
  • Faster than lists
  • Good for fixed data

✔ Syntax

t = (10, 20, 30)

✔ Accessing Elements

print(t[1])

✔ Tuple Packing/Unpacking

a, b, c = t

✔ Use Cases

  • Configuration values
  • Coordinates (x, y)
  • Data that should not change

✔ Time Complexity

Operation Complexity
Indexing O(1)
Search O(n)

🟨 3. SET

A set is an unordered collection with unique values.

✔ Features

  • Unordered
  • Mutable
  • Removes duplicates automatically
  • Very fast for membership tests
  • Uses Hash Table internally

✔ Syntax

s = {1, 2, 3, 4}

✔ Set Operations

A = {1, 2, 3}
B = {3, 4, 5}

print(A | B)   # Union
print(A & B)   # Intersection
print(A - B)   # Difference
print(A ^ B)   # Symmetric Difference

✔ Time Complexity

Operation Complexity
Insert O(1)
Delete O(1)
Search O(1)

🟦 4. DICTIONARY

A dictionary stores data in key–value pairs.

✔ Features

  • Unordered (but maintains insertion order since Python 3.7+)
  • Keys must be unique
  • Mutable
  • Uses Hash Table internally
  • Very fast lookup

✔ Syntax

person = {
    "name": "Meenu",
    "age": 21
}

✔ Accessing Values

print(person["name"])

✔ Useful Dictionary Methods

Method Description
get() Returns value safely
items() Returns (key, value) pairs
keys() Returns keys
values() Returns values
update() Modify dictionary

✔ Time Complexity

Operation Complexity
Access O(1)
Insert O(1)
Delete O(1)

🟪 Advanced Data Structures in Python (collections module)

1. deque (double-ended queue)

Faster append/pop from both ends than lists.

from collections import deque

d = deque([1, 2, 3])
d.appendleft(0)
d.append(4)

2. namedtuple

Tuple with named fields (readable + lightweight).

from collections import namedtuple

Point = namedtuple("Point", "x y")
p = Point(10, 20)
print(p.x, p.y)

3. Counter

Counts frequency of elements.

from collections import Counter

c = Counter("banana")
print(c)

4. defaultdict

Provides default values for missing keys.

from collections import defaultdict

d = defaultdict(int)
d["a"] += 1

5. OrderedDict

Remember old insertion order (before Python 3.7).


🟥 Other Important Data Structures

1. Heap (heapq)

A min-heap structure used for priority queues.

import heapq

nums = [10, 5, 20]
heapq.heapify(nums)

2. Array (array module)

Efficient for large numeric datasets.

from array import array
a = array('i', [1,2,3])

3. Stack

Can be implemented using:

  • List
  • deque

Example (stack using list)

stack = []
stack.append(10)
stack.pop()

4. Queue

Can be implemented using queue.Queue.

from queue import Queue
q = Queue()
q.put(10)
q.get()

🧩 Custom Data Structures

Python can also implement:

  • Linked List
  • Tree
  • Binary Search Tree
  • Graph
  • Hash Table
  • Trie

Example: Simple Node of Linked List

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

📊 Comparison Table of Built-in Data Structures

Feature List Tuple Set Dict
Ordered Yes Yes No Yes
Mutable Yes No Yes Yes
Duplicates Yes Yes No Keys—No
Indexed Yes Yes No No
Speed Slow Fast Fast Fast

🔍 Real-Life Use Cases

Data Structure Example
List To-do list, playlist
Tuple Coordinates, config values
Set Unique visitors on website
Dictionary Contacts: name → phone
Counter Character frequency
Heap Job scheduling, priority tasks

⭐ Want More?

I can also provide:

✅ PDF notes
✅ Interview questions
✅ Coding exercises
✅ Diagram images
✅ Short notes for exa


Post a Comment

0 Comments