Python Data Structures: Code Ko Fast Aur Easy Kaise Banaye?

Ek kahani jo aapke code ko badal degi
Character: Professor Py - An elderly, wise-looking character with glasses and Python logo on shirt

Kahani Ki Shuruat
Ek coding bootcamp mein, Professor Py ne apne naye students ko ek challenge diya. "Aaj hum seekhenge ki Python data structures kaise aapke code ko fast aur efficient bana sakte hain," unhone kaha, board par "Data Structures" likhte huye.
Classroom mein teen students the - Lisha, jo ek beginner thi; Rohan, jo thoda experienced tha; aur Vikram, jo khud ko expert manta tha. Professor Py ne aaj sabko ek real-world problem solve karne ko kaha - ek bade dataset se duplicates remove karne ka task.
Character: Lisha - A curious young woman with notebook and pen, looking eager to learn

Lists ka Lesson
"Main toh sirf list use karungi," Lisha ne confident hokar kaha. "Lists toh sabse easy hain."
Usne apna code likha:
def remove_duplicates(data):
result = []
for item in data:
if item not in result:
result.append(item)
return result
# Test with a small dataset
sample_data = [5, 2, 3, 2, 1, 5, 1, 7, 8, 5]
print(remove_duplicates(sample_data)) # Output: [5, 2, 3, 1, 7, 8]
Professor Py ne muskurate hue kaha, "Bilkul sahi, Lisha! Lists Python mein sabse basic data structure hain. Lekin jab data bada hota hai, tab kya hoga?"
Unhone projector par ek graph dikhaya jisme list ke performance ko visualize kiya gaya tha. "Lists mein in operation O(n) time complexity leta hai, matlab har item check karne ke liye puri list scan hoti hai. 10 items ke liye 10 checks, 100 items ke liye 100 checks, aur agar millions mein data ho toh...?"
Graph showing performance degradation of lists with increasing data size
![![Graph showing performance degradation of lists with increasing data size]](https://s3.amazonaws.com/powerdrill-s3/tmp_datasource_cache/image/a078d051-f977-4658-810a-044c0950a9d7.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20250428T173709Z&X-Amz-SignedHeaders=host&X-Amz-Expires=600&X-Amz-Credential=AKIARLSQLXURHEIDN4OZ%2F20250428%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=345e944983a756d50bbe17ceab2ea3b738296dea6a405eb1213e335205ae43ba)
Lisha ke chehre par chinta ki lakeer dikhi. "Toh bade data ke liye list efficient nahi hai?"
Sets ka Secret
Character: Rohan - A confident young man with casual attire and a laptop

"Main ise sets se solve karunga," Rohan ne haath uthate hue kaha. Usne apna solution share kiya:
def remove_duplicates_fast(data):
return list(set(data))
# Same test
sample_data = [5, 2, 3, 2, 1, 5, 1, 7, 8, 5]
print(remove_duplicates_fast(sample_data)) # Output: [1, 2, 3, 5, 7, 8]
"Wah Rohan! Tumne code ko na sirf chhota kiya, balki fast bhi," Professor Py ne praise kiya. "Sets Python mein hash tables use karte hain, jisse in operation ka time complexity O(1) ho jata hai - matlab data kitna bhi bada ho, checking ka time almost constant rehta hai."
Professor ne dusra graph dikhaya jisme list aur set ka comparison tha. Sets ki line almost flat thi, jabki list ki line data size ke sath tezi se upar ja rahi thi.
Graph comparing performance of lists vs sets with increasing data size

"Lekin ek problem hai," Professor ne bataya. "Sets order maintain nahi karte. Notice karo ki output ka order input se alag hai."
Dictionaries ka Dramaا
Character: Vikram - An overconfident student with stylish glasses and a smug expression

"Main toh dictionaries se solve karunga," Vikram ne announce kiya. "Woh sets se bhi powerful hain."
def remove_duplicates_with_order(data):
seen = {}
result = []
for item in data:
if item not in seen:
seen[item] = True
result.append(item)
return result
# Test with order preservation
sample_data = [5, 2, 3, 2, 1, 5, 1, 7, 8, 5]
print(remove_duplicates_with_order(sample_data)) # Output: [5, 2, 3, 1, 7, 8]
"Excellent, Vikram!" Professor Py khushi se bole. "Dictionaries bhi hash tables par based hain, isliye inki lookup speed sets ki tarah hi O(1) hoti hai. Plus, humne order bhi maintain kar liya."
Professor ne whiteboard par ek table draw kiya, jisme different operations ki time complexity compare ki gayi thi:
| Operation | List | Set | Dictionary |
| Access | O(1) | N/A | O(1) |
| Search | O(n) | O(1) | O(1) |
| Insertion | O(1) | O(1) | O(1) |
| Deletion | O(n) | O(1) | O(1) |
Real-World Performance Test
"Ab theory se practice par aate hain," Professor ne kaha. "In teeno approaches ko 1 million items par test karte hain."
Unhone projector par results dikhaye:
import time
import random
# Generate large dataset with duplicates
large_data = [random.randint(0, 100000) for _ in range(1000000)]
# Test list approach
start = time.time()
list_result = remove_duplicates(large_data)
list_time = time.time() - start
print(f"List approach took: {list_time:.2f} seconds")
# Test set approach
start = time.time()
set_result = remove_duplicates_fast(large_data)
set_time = time.time() - start
print(f"Set approach took: {set_time:.2f} seconds")
# Test dictionary approach
start = time.time()
dict_result = remove_duplicates_with_order(large_data)
dict_time = time.time() - start
print(f"Dictionary approach took: {dict_time:.2f} seconds")
Results:
List approach: 263.45 seconds
Set approach: 0.23 seconds
Dictionary approach: 0.27 seconds
Bar graph showing dramatic performance difference between list vs set/dictionary

Classroom mein silence chha gaya. List approach set aur dictionary se lakhon guna slower tha!
Collections Module ka Cameo
"Aur ek special guest hai," Professor Py muskuraye. "Python ki collections module! Isme OrderedDict hai jo Python 3.6+ mein dictionaries ki tarah order preserve karta hai, aur Counter jo duplicates count karne mein madad karta hai."
from collections import OrderedDict, Counter
# Using OrderedDict for removing duplicates while preserving order
def remove_duplicates_ordered(data):
return list(OrderedDict.fromkeys(data))
# Using Counter to find frequencies
def find_frequencies(data):
return Counter(data)
# Test
sample_data = [5, 2, 3, 2, 1, 5, 1, 7, 8, 5]
print(remove_duplicates_ordered(sample_data)) # Output: [5, 2, 3, 1, 7, 8]
print(find_frequencies(sample_data)) # Output: Counter({5: 3, 2: 2, 1: 2, 3: 1, 7: 1, 8: 1})
Character: All three students looking amazed at the magic of collections module

Specialized Data Structures
"Aur advanced kaam ke liye," Professor ne continue kiya, "Python mein specialized data structures bhi hain:"
# Queue implementation using deque
from collections import deque
queue = deque(["Task 1", "Task 2", "Task 3"])
queue.append("Task 4") # Add to right
task = queue.popleft() # Remove from left (FIFO)
print(f"Processing: {task}") # Output: Processing: Task 1
# Priority Queue
import heapq
tasks = [(3, "Medium priority"), (1, "High priority"), (5, "Low priority")]
heapq.heapify(tasks)
next_task = heapq.heappop(tasks)
print(f"Next task: {next_task[1]}") # Output: Next task: High priority
Kahani ka Conclusion
Class khatam hone se pehle, Professor Py ne sabse pucha ki aaj ka sabse important lesson kya tha.
Character: All students raising hands enthusiastically

Lisha ne haath uthaya: "Right data structure choose karna utna hi important hai jitna right algorithm choose karna!"
Rohan ne add kiya: "Aur data ka size aur pattern bhi consider karna zaroori hai!"
Vikram, ab thoda humble, ne kaha: "Time complexity understanding se hum predict kar sakte hain ki konsa approach scale karega aur konsa nahi."
Professor Py ne satisfied hokar kaha, "Perfect! Data structures code ko sirf clean hi nahi, balki dramatically faster bhi banate hain. Yaad rakhein - har problem ke liye:
Data ka size aur pattern analyze karein
Operations identify karein jo aap frequently perform karenge
Time aur space complexity ke hisaab se right data structure choose karein
Built-in modules ka fayda uthayein
Kya aap bhi apne code ko optimize karne ke liye sahi data structures use kar rahe hain?
#chaicode




