WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Python · Advanced · question 42 of 100

How do you use Python’s itertools module? Provide examples of using some of its functions.?

📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

The itertools module in Python is a collection of tools for working with iterators and iterable objects. It provides a range of functions that can be used to create and manipulate iterators in various ways. Here are some examples of using functions from the itertools module:

    import itertools
    
    # create an infinite iterator that repeats a sequence
    iterator1 = itertools.cycle([1, 2, 3])
    for i in range(5):
        print(next(iterator1))
    
    # create an iterator that returns values from several iterables in order
    iterator2 = itertools.chain([1, 2, 3], ['a', 'b', 'c'], ['X', 'Y', 'Z'])
    for value in iterator2:
        print(value)
    
    # create an iterator that returns combinations of elements from an iterable
    iterator3 = itertools.combinations(['a', 'b', 'c'], 2)
    for combination in iterator3:
        print(combination)
    
    # create an iterator that returns permutations of elements from an iterable
    iterator4 = itertools.permutations(['a', 'b', 'c'], 2)
    for permutation in iterator4:
        print(permutation)
    
    # create an iterator that returns the Cartesian product of several iterables
    iterator5 = itertools.product([1, 2], ['a', 'b'], [True, False])
    for product in iterator5:
        print(product)

In this example, we use the itertools module to create iterators that repeat a sequence, chain together several iterables, generate combinations and permutations of elements from an iterable, and compute the Cartesian product of several iterables.

Other useful functions from the itertools module include islice, which returns a slice of an iterator, groupby, which groups elements from an iterator based on a key function, and accumulate, which generates a running total or other accumulated value from an iterable.

The itertools module provides a powerful set of tools for working with iterators in Python. By using functions from this module, you can efficiently create, combine, and manipulate iterators to perform complex tasks with ease.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Python interview — then scores it.
📞 Practice Python — free 15 min
📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

All 100 Python questions · All topics