Thursday, 23 May 2024

13 Powerful Python Features You're Probably Not Using Enough

Python is a versatile and powerful language, and while many developers use it extensively, there are numerous features that often go underutilized.

List Comprehensions

List comprehensions provide a concise way to create lists. This can replace the need for using loops to generate lists.

squares = [x**2 for x in range(10)]

Generator Expressions

Similar to list comprehensions but with parentheses, generator expressions are used for creating generators. These are memory-efficient and suitable for large data sets.

squares_gen = (x**2 for x in range(10))

Default Dictionary

The defaultdict from the collections module is a dictionary-like class that provides default values for missing keys.

from collections import defaultdict

dd = defaultdict(int)

dd['key'] += 1

Named Tuples

namedtuple creates tuple subclasses with named fields. This makes code more readable by accessing fields by name instead of position.

from collections import namedtuple

Point = namedtuple('Point', 'x y')

p = Point(10, 20)

Enumerate Function

The enumerate function adds a counter to an iterable and returns it as an enumerate object. This is useful for obtaining both the index and the value in a loop.

for index, value in enumerate(['a', 'b', 'c']):

    print(index, value)

Zip Function

The zip function combines multiple iterables into a single iterable of tuples. This is useful for iterating over multiple sequences simultaneously.

names = ['a', 'b', 'c']

ages = [20, 25, 30]

combined = list(zip(names, ages))


Set Comprehensions

Similar to list comprehensions, set comprehensions create sets in a concise way.

unique_squares = {x**2 for x in range(10)}

Frozenset

A frozenset is an immutable set. It's useful when you need a set that cannot be changed after creation.

fs = frozenset([1, 2, 3, 2, 1])



Counter

The Counter class from the collections module counts the occurrences of elements in a collection. It's useful for counting hashable objects.

from collections import Counter

counts = Counter(['a', 'b', 'c', 'a', 'b', 'b'])

Context Managers

Using the with statement, context managers handle resource management, like file I/O, efficiently and cleanly.

with open('file.txt', 'r') as file:

    contents = file.read()



dataclass

The dataclass decorator simplifies class creation by automatically adding special methods like init and repr.

from dataclasses import dataclass

@dataclass

class Point:

    x: int

    y: int



Decorators

Decorators are functions that modify the behavior of other functions. They are useful for logging, access control, memoization, and more.

def my_decorator(func):

    def wrapper():

        print("Something is happening before the function is called.")

        func()

        print("Something is happening after the function is called.")

    return wrapper

@my_decorator

def say_hello():

    print("Hello!")

Asyncio

The asyncio module provides a framework for asynchronous programming. This is useful for I/O-bound and high-level structured network code.

import asyncio

async def main():

    print('Hello')

    await asyncio.sleep(1)

    print('World')

asyncio.run(main())



0 Comments:

Post a Comment

Popular Posts

Categories

AI (33) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (146) C (77) C# (12) C++ (82) Course (67) Coursera (198) Cybersecurity (24) data management (11) Data Science (106) Data Strucures (8) Deep Learning (13) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (21) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Nvidia (1) Pandas (3) PHP (20) Projects (29) Python (893) Python Coding Challenge (285) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses