๐ Itertools
This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
import itertools # 1. chain โ combine multiple iterables seamlessly python_topics = ["Variables", "Functions", "Classes"] ai_topics = ["ML", "Deep Learning", "LLMs"] devops_topics = ["Docker", "CI/CD"] all_topics = list(itertools.chain(python_topics, ai_topics, devops_topics)) print("All topics:", all_topics) # 2. product โ cartesian product (all combinations) levels = ["Beginner", "Advanced"] courses = ["Python", "AI"] combos = list(itertools.product(levels, courses)) print("\nCourse combos:") for c in combos: print(f" {c[0]} {c[1]}") # 3. combinations & permutations mentors = ["santoshtvk", "dhruv", "tvk"] print("\nMentor pairs (combinations):") for pair in itertools.combinations(mentors, 2): print(" ", pair) # 4. groupby โ group sorted data from operator import itemgetter students = [ {"name": "santoshtvk", "course": "Python"}, {"name": "dhruv", "course": "AI"}, {"name": "tvk", "course": "Python"}, {"name": "alice", "course": "AI"}, ] students_sorted = sorted(students, key=itemgetter("course")) print("\nGrouped by course:") for course, group in itertools.groupby(students_sorted, key=itemgetter("course")): names = [s["name"] for s in group] print(f" {course}: {names}") # 5. islice โ take first N from an infinite generator def counter_from(n): while True: yield n n += 1 first_10 = list(itertools.islice(counter_from(100), 10)) print("\nFirst 10 from 100:", first_10) # 6. accumulate โ running totals import itertools, operator monthly_revenue = [45000, 52000, 48000, 61000, 75000, 89000] cumulative = list(itertools.accumulate(monthly_revenue)) print("\nCumulative revenue:", cumulative) peak = max(zip(cumulative, range(1, 13)), key=itemgetter(0))
Keep exploring and happy coding! ๐ป