Day 5: Python's collections Module - When & Why to Use It? ??

Python's collections module provides specialized data structures with better performance and functionality than standard lists, tuples, and dictionaries. ??

Today, I'll explore some of the most useful collections classes and show you when and why to use them! ??


1?? Counter - Counting Made Easy

Used for counting hashable objects (like list elements or characters in a string)

from collections import Counter

words = ["apple", "banana", "apple", "orange", "banana", "banana"]
word_count = Counter(words)
print(word_count)   # Couter({'banana': 3, 'apple': 2, 'orange': 1})        

?? When to use?

?? Counting elements in a list or string

?? Finding the most common items

?? Quick frequency analysis


2?? defaultdict - Avoid Key Errors in Dictionaries

A defaultdict provides a default value when a key is missing, avoiding KeyError

? Example: Grouping Data

from collections import defaultdict

grouped_data = defaultdict(list)
data=[("fruit","apple"), ("fruit","banana"), ("vegetable","carrot")]

for category, item in data:
    grouped_data[category].append(item)

print(grouped_data)           

?? When to use?

?? Avoiding KeyError

?? Creating grouped dictionaries dynamically

?? Initializing missing keys with default values


3?? deque - Faster Lists for Insertions & Deletions

A deque (double-ended queue) allows fast appends and pops from both ends O(1) complexity

? Example: Efficient Queue Implementation

from collections import deque

queue = deque(["A", "B", "C"])
queue.append("D")  # add to end
queue.appendleft("Z")  # add to front
print(queue)   # deque(['Z', 'A', 'B', 'C', 'D'])

queue.pop()  # Remove from end
queue.popleft()  # Remove from front        

?? When to use?

?? Implementing queues or stacks efficiently

?? Handling large datasets with frequent insertions/removals

?? Faster that list.append() ad list.pop(0)


4?? namedtuple - Readable Tuples with Names

A namedtuple gives tuples named attributes, making them more readable than regular tuples

? Example: Creating a Named Tuple

from collections import namedtuple

Person =  namedtuple("Person", ["name", "age"])
person1 = Person(name="Jyothsna", age=25)

print(person1.name)  # Jyothsna
print(person1.age)  # 25        

?? When to use?

?? When we need lightweight objects without a full class

?? Making code more readable with named attributes

?? Storing database rows, coordinates, etc


5?? OrderedDict - Keep Dictionary Order (Before Python 3.7)

An OrderedDict remembers the insertion order of keys (useful in Python < 3.7, where normal dicts didn't maintain order)

? Example: Preserving Order

from collections import OrderedDict

ordered_dict = OrderedDict()
ordered_dict["b"] = 2
ordered_dict["a"] = 1
ordered_dict["c"] = 3

print(ordered_dict)  # Maintains order of insertion        

?? When to use?

?? When using Python before 3.7 (now, regular dict maintains order)

?? Keeping insertion order for specific applications


Summary of collections Module

?? Counter - Quick frequency counts

?? defaultdict - Avoid missing key errors

?? deque - Faster list operations

?? namedtuple - Readable tuples

?? OrderedDict - Maintains order

#100DaysOfCode #Python #Collections #Programming #Coding


要查看或添加评论,请登录

Sarasa Jyothsna Kamireddi的更多文章

  • Day 32: Using DISTINCT in MySQL

    Day 32: Using DISTINCT in MySQL

    Today, let us explore the DISTINCT keyword in MySQL, which helps in retrieving unique values from a column. It's a…

  • Day 31: Aggregation Functions (Count, AVG, SUM) in MySQL

    Day 31: Aggregation Functions (Count, AVG, SUM) in MySQL

    Today, let us explore aggregation functions in MySQL, which are used to perform calculations on multiple rows and…

  • Day 30: Limiting Data with LIMIT in MySQL

    Day 30: Limiting Data with LIMIT in MySQL

    Today, let us explore the LIMIT clause in MySQL, which helps control the number of records retrieved from a query. It's…

  • Day 29: Sorting Results with ORDER BY in MySQL

    Day 29: Sorting Results with ORDER BY in MySQL

    Today, let us explore the ORDER BY clause in MySQL. This clause sorts query results in ascending or descending order…

  • Day 28: Filtering Data with LIKE in MySQL

    Day 28: Filtering Data with LIKE in MySQL

    Today, let us explore the LIKE operator in MySQL, which is used for pattern matching in text-based searches. It's super…

  • Day 27: Filtering Data with WHERE

    Day 27: Filtering Data with WHERE

    Today, let us explore the WHERE clause in MySQL, which helps filter records based on specific conditions The WHERE…

  • Day 26: Basic MySQL Commands

    Day 26: Basic MySQL Commands

    Today, let us explore some fundamental MySQL commands that are essential for database management 1. Creating a Database…

  • Day 25: MySQL Installation

    Day 25: MySQL Installation

    Steps to Install MySQL: ? Download MySQL: Go to MySQL Official Website and choose the appropriate version for your OS…

  • Day 24: Introduction to MySQL

    Day 24: Introduction to MySQL

    Today, let us dive into MySQL, a powerful Relational Database Management System (RDBMS) that helps store and manage…

  • Day 23: Error Handling Best Practice in Python

    Day 23: Error Handling Best Practice in Python

    Proper error handling makes our python code more robust, readable, and maintainable. Here are the best practices to…

社区洞察

其他会员也浏览了