Connect with us

Jobs & Careers

Python functools & itertools: 7 Super Handy Tools for Smarter Code

Published

on



Image by Author | Ideogram

 

Python’s standard library has several utilities that can transform your code from clunky and verbose to elegant and efficient. Among these, the functools and itertools modules often come in super handy for non-trivial tasks.

Today, we’ll look at seven essential tools — functions and decorators — from these modules that’ll make your Python code better.

Let’s get started.

🔗 Link to the code on GitHub

 

1. functools.lru_cache

 
You can use the @lru_cache decorator to cache function results, and to avoid repeating expensive operations.

Here’s an example:

from functools import lru_cache

@lru_cache(maxsize=128)
def fetch_user_data(user_id):
    # Expensive database call
    return database.get_user(user_id)

# First call hits database, subsequent calls use cache
user = fetch_user_data(123)  # Database call
user = fetch_user_data(123)  # Returns cached result

 

How it works: The @lru_cache decorator stores results in memory. When fetch_user_data(123) is called again, it returns the cached result instead of hitting the database. maxsize=128 keeps the 128 most recent results.

 

2. itertools.chain

 
To process multiple iterables as one continuous stream, you can use chain.from_iterable() from the itertools module.

Let’s take an example:

from itertools import chain

# Process multiple log files as one stream
error_logs = ['app.log', 'db.log', 'api.log']
all_lines = chain.from_iterable(open(f) for f in error_logs)

error_count = sum(1 for line in all_lines if 'ERROR' in line)

 

How it works: chain.from_iterable() takes multiple iterables and creates one continuous stream. It reads one line at a time.

 

3. functools.partial

 
Partial functions in Python are super helpful when you need to create specialized versions of functions. Meaning you’d like to create versions of the function with some arguments already set using partial from the functools module.

Here’s an example of a partial function:

from functools import partial
import logging

def log_event(level, component, message):
    logging.log(level, f"[{component}] {message}")

# Create specialized loggers
auth_error = partial(log_event, logging.ERROR, 'AUTH')
db_info = partial(log_event, logging.INFO, 'DATABASE')

# Clean usage
auth_error("Login failed for user")
db_info("Connection established")

 

How it works: partial creates a new function with some arguments pre-filled. In the example, auth_error is essentially log_event with level and component already set, so you only need to provide the message.

 

4. itertools.combinations

 
When you need to generate all possible combinations of items for testing or optimization, you can use combinations from the itertools module.

Consider the following example:

from itertools import combinations

features = ['cache', 'compression', 'cdn']

# Test all pairs of features
for combo in combinations(features, 2):
    performance = test_feature_combo(combo)
    print(f"{combo}: {performance}ms")

 

How it works: combinations(features, 2) generates all possible pairs from the list. It creates combinations on-demand without storing them all in memory, making it efficient for large datasets.

 

5. functools.singledispatch

 
The @singledispatch decorator from the functools module can help you make functions that act differently based on input type.

Look at the following code snippet:

from functools import singledispatch
from datetime import datetime

@singledispatch
def format_data(value):
    return str(value)  # Default

@format_data.register(datetime)
def _(value):
    return value.strftime("%Y-%m-%d")

@format_data.register(list)
def _(value):
    return ", ".join(str(item) for item in value)

# Automatically picks the right formatter
print(format_data(datetime.now()))  # this outputs "2025-06-27"
print(format_data([1, 2, 3]))       # this outputs "1, 2, 3"

 

How it works: Python checks the type of the first argument and calls the appropriate registered function. However, it uses the default @singledispatch function if no specific handler exists.

 

6. itertools.groupby

 
You can group consecutive elements that share the same property using the groupby function from itertools.

Consider this example:

from itertools import groupby

transactions = [
    {'type': 'credit', 'amount': 100},
    {'type': 'credit', 'amount': 50},
    {'type': 'debit', 'amount': 75},
    {'type': 'debit', 'amount': 25}
]

# Group by transaction type
for trans_type, group in groupby(transactions, key=lambda x: x['type']):
    total = sum(item['amount'] for item in group)
    print(f"{trans_type}: ${total}")

 

How it works: groupby groups consecutive items with the same key. It returns pairs of (key, group_iterator). Important: it only groups adjacent items, so sort your data first if needed.

 

7. functools.reduce

 
You can use the reduce function from the functools module to apply a function cumulatively to all elements in an iterable to get a single value.

Take the following example:

from functools import reduce

# Calculate compound interest
monthly_rates = [1.01, 1.02, 0.99, 1.015]  # Monthly growth rates

final_amount = reduce(lambda total, rate: total * rate, monthly_rates, 1000)
print(f"Final amount: ${final_amount:.2f}")

 

How it works: reduce takes a function and applies it step by step: first to the initial value (1000) and the first rate, then to that result and the second rate, and so on. It works well for operations that build up state.

 

Wrapping Up

 
To sum up, we’ve seen how you can use:

  • @lru_cache when you have functions that are called often with the same arguments
  • itertools.chain when you need to process multiple data sources as one continuous stream
  • functools.partial to create specialized versions of generic functions
  • itertools.combinations for systematic exploration of possibilities
  • @singledispatch when you need type-based function behavior
  • groupby for efficient consecutive grouping operations
  • reduce for complex aggregations that build up state

The next time you find yourself writing verbose loops or repetitive code, pause and consider whether one of these might provide a more elegant solution.

These are just a handful of tools I find helpful. There are many more if you take a closer look at the Python standard library. So yeah, happy exploring!
 
 

Bala Priya C is a developer and technical writer from India. She likes working at the intersection of math, programming, data science, and content creation. Her areas of interest and expertise include DevOps, data science, and natural language processing. She enjoys reading, writing, coding, and coffee! Currently, she’s working on learning and sharing her knowledge with the developer community by authoring tutorials, how-to guides, opinion pieces, and more. Bala also creates engaging resource overviews and coding tutorials.





Source link

Continue Reading
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Jobs & Careers

Canva Partners With NCERT to Launch AI-Powered Teacher Training

Published

on


Canva has signed a memorandum of understanding (MoU) with the National Council of Educational Research and Training (NCERT) to launch free teacher training and certification programs hosted on the education ministry’s DIKSHA platform. 

The initiative aims to enhance digital literacy, creativity, and AI proficiency among educators across India, in alignment with the objectives of the National Education Policy (NEP) 2020.

As part of the agreement, Canva will offer Indian teachers free access to its education platform and provide learning materials tailored for visual and collaborative instruction. NCERT will ensure that the course content aligns with the national curriculum and is made regionally accessible. Available in multiple Indian languages, the course will also be broadcast via PM e-Vidya DTH channels to extend its reach beyond internet-enabled classrooms.

The certification program includes training on using Canva’s design tools to create engaging lesson plans, infographics, and presentations. Teachers will also learn to co-create content with students and apply AI tools to improve classroom outcomes. Upon completion, participants will receive a joint certificate from NCERT and Canva.

“This partnership is a powerful step toward equipping educators with practical digital skills that not only save time but spark imagination in every classroom,” Jason Wilmot, head of education at Canva, said in a press statement.

Chandrika Deb, country manager for India at Canva stated, “By delivering this program free of cost, in multiple languages, and through a trusted national platform like NCERT, we are not only advancing digital fluency and creative confidence in classrooms across the country, but also deepening Canva’s long-term commitment to India, which plays a pivotal role in our vision to democratize design and creativity at scale.”

Moreover, the company shared some interesting figures. Canva has seen significant global momentum, with over 100 million students and teachers using its platform. In 2024, over 1 billion designs were created, many powered by Canva’s AI tools like Dream Lab, which enables teachers to generate custom visuals instantly. Teacher usage of AI tools has increased by 50% over the past year, with student engagement rising by 107%.

We may see further developments in this partnership as the training program for teachers progresses over time.



Source link

Continue Reading

Jobs & Careers

Capgemini to Acquire WNS for $3.3 Billion with Focus on Agentic AI

Published

on


Capgemini has announced a definitive agreement to acquire WNS, a mid-sized Indian IT firm, for $3.3 billion in cash. This marks a significant step towards establishing a global leadership position in agentic AI.

The deal, unanimously approved by the boards of both companies, values WNS at $76.50 per share—a premium of 28% over the 90-day average and 17% above the July 3 closing price.

The acquisition is expected to immediately boost Capgemini’s revenue growth and operating margin, with normalised EPS accretion of 4% by 2026, increasing to 7% post-synergies in 2027.

“Enterprises are rapidly adopting generative AI and agentic AI to transform their operations end-to-end. Business process services (BPS) will be the showcase for agentic AI,” Aiman Ezzat, CEO of Capgemini, said. 

“Capgemini’s acquisition of WNS will provide the group with the scale and vertical sector expertise to capture that rapidly emerging strategic opportunity created by the paradigm shift from traditional BPS to agentic AI-powered intelligent operations.”

Pending regulatory approvals, the transaction is expected to close by the end of 2025.

WNS’ integration is expected to strengthen Capgemini’s presence in the US market while unlocking immediate cross-selling opportunities through its combined offerings and clientele. 

WNS, which reported $1.27 billion in revenue for FY25 with an 18.7% operating margin, has consistently delivered a revenue growth of around 9% over the past three fiscal years.

“As a recognised leader in the digital BPS space, we see the next wave of transformation being driven by intelligent, domain-centric operations that unlock strategic value for our clients,” Keshav R Murugesh, CEO of WNS, said. “Organisations that have already digitised are now seeking to reimagine their operating models by embedding AI at the core—shifting from automation to autonomy.”

The companies expect to drive additional revenue synergies between €100 million and €140 million, with cost synergies of up to €70 million annually by the end of 2027. 

“WNS and Capgemini share a bold, future-focused vision for Intelligent Operations. I’m confident that Capgemini is the ideal partner at the right time in WNS’ journey,” Timothy L Main, chairman of WNS’ board of directors, said.

Capgemini, already a major player with over €900 million in GenAI bookings in 2024 and strategic partnerships with Microsoft, Google, AWS, Mistral AI, and NVIDIA, aims to solidify its position as a transformation partner for businesses looking to embed agentic AI at scale.



Source link

Continue Reading

Jobs & Careers

Piyush Goyal Announces Second Tranche of INR 10,000 Cr Deep Tech Fund

Published

on


IIT Madras and its alumni association (IITMAA) held the sixth edition of their global innovation and alumni summit, ‘Sangam 2025’, in Bengaluru on 4 and 5 July. The event brought together over 500 participants, including faculty, alumni, entrepreneurs, investors and students.

Union Commerce and Industry Minister Shri Piyush Goyal, addressing the summit, announced a second tranche of ₹10,000 crore under the government’s ‘Fund of Funds’, this time focused on supporting India’s deep tech ecosystem. “This money goes to promote innovation, absorption of newer technologies and development of contemporary fields,” he said. 

The Minister added that guidelines for the fund are currently being finalised, to direct capital to strengthen the entire technology lifecycle — from early-stage research through to commercial deployment, not just startups.. 

He also referred to the recent Cabinet decision approving $12 billion (₹1 lakh crore) for the Department of Science and Technology in the form of a zero-interest 50-year loan. “It gives us more flexibility to provide equity support, grant support, low-cost support and roll that support forward as technologies get fine-tuned,” he said.

Goyal said the government’s push for indigenous innovation stems from cost advantages as well. “When we work on new technologies in India, our cost is nearly one-sixth, one-seventh of what it would cost in Switzerland or America,” he said.

The Minister underlined the government’s focus on emerging technologies such as artificial intelligence, machine learning, and data analytics. “Today, our policies are structured around a future-ready India… an India that is at the forefront of Artificial Intelligence, Machine Learning, computing and data analytics,” he said.

He also laid out a growth trajectory for the Indian economy. “From the 11th largest GDP in the world, we are today the fifth largest. By the end of Calendar year 2025, or maybe anytime during the year, we will be the fourth-largest GDP in the world. By 2027, we will be the third largest,” Goyal said.

Sangam 2025 featured a pitch fest that saw 20 deep tech and AI startups present to over 250 investors and venture capitalists. Selected startups will also receive institutional support from the IIT Madras Innovation Ecosystem, which has incubated over 500 ventures in the last decade.

Key speakers included Aparna Chennapragada (Chief Product Officer, Microsoft), Srinivas Narayanan (VP Engineering, OpenAI), and Tarun Mehta (Co-founder and CEO, Ather Energy), all IIT Madras alumni. The summit also hosted Kris Gopalakrishnan (Axilor Ventures, Infosys), Dr S. Somanath (former ISRO Chairman) and Bengaluru South MP Tejasvi Surya.

Prof. V. Kamakoti, Director, IIT Madras, said, “IIT Madras is committed to playing a pivotal role in shaping ‘Viksit Bharat 2047’. At the forefront of its agenda are innovation and entrepreneurship, which are key drivers for National progress.”

Ms. Shyamala Rajaram, President of IITMAA, said, “Sangam 2025 is a powerful confluence of IIT Madras and its global alumni — sparking bold conversations on innovation and entrepreneurship.”

Prof. Ashwin Mahalingam, Dean (Alumni and Corporate Relations), IIT Madras, added, “None of this would be possible without the unwavering support of our alumni community. Sangam 2025 embodies the strength of that network.”



Source link

Continue Reading

Trending