Python Mastery – From Basics to Brilliance / Advanced Python Topics

enumerate() and useful itertools

✅ enumerate()

💬 What it does:

Adds a counter (index) to each item in a list or any iterable.

names = ["Alice", "Bob", "Charlie"]
for index, name in enumerate(names):
    print(index, name)
0 Alice
1 Bob
2 Charlie

💡 Why use it?

Instead of writing:

for i in range(len(names)):
    print(i, names[i])

You can use enumerate() to make it cleaner and more readable.


🧰 itertools — Powerful Tools for Iteration

The itertools module provides fast, memory-efficient tools for looping, especially when dealing with combinations, infinite sequences, or repeated patterns.


✅ count(start, step)

Keeps counting forever, starting from start, with a gap of step.

import itertools

for i in itertools.count(10, 2):  # 10, 12, 14...
    if i > 20:
        break
    print(i)
10
12
14
16
18
20

🧠 Use case: Generating invoice numbers, timestamps, etc.


✅ cycle(iterable)

Loops through the values endlessly.

for i, value in enumerate(itertools.cycle(["A", "B", "C"])):
    if i == 6:
        break
    print(value)
A
B
C
A
B
C

🧠 Use case: Rotating banners, music playlists.


✅ repeat(elem, times)

Repeats a value multiple times.

for x in itertools.repeat("Hello", 3):
    print(x)
Hello
Hello
Hello

🧠 Use case: Placeholder values, mocking data.


✅ chain()

Combines multiple iterables into one.

from itertools import chain
print(list(chain([1, 2], [3, 4])))  # [1, 2, 3, 4]

🧠 Use case: Merging multiple data lists.


✅ combinations() and permutations()

from itertools import combinations, permutations

items = ["a", "b", "c"]
print(list(combinations(items, 2)))   # No repetition, no reverse
print(list(permutations(items, 2)))   # All orderings
[('a', 'b'), ('a', 'c'), ('b', 'c')]   # combinations
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]  # permutations

🧠 Use case:

  • Combinations: Forming teams or pairs

  • Permutations: Shuffling passwords, game possibilities


⚡ Why itertools matters?

✅ Efficient

✅ Works well with large or infinite sequences

✅ Reduces boilerplate code