Search code examples
pythonpython-itertools

Intersperse list with a step


I have a list of posts `[Post1, Post2, Post3, Post4, ..., PostN] and I need to intersperse it with advertisement (basically, insert after N posts). For example:

step = 3
insert_advertisement(posts_list, advertisement, step) # Insert advertisement after 3 posts

Output:

[Post1, Post2, Post3, advertisement, Post4, Post5, Post6, advertisement, ...]

Is there nifty way to implement this with itertools? If not - then I'll appreciate any other solution.


Solution

  • Using a generator function:

    >>> def insert_advertisement(posts_list, advertisement, step):
    ...     for i, post in enumerate(posts_list):
    ...         if i > 0 and i % step == 0:
    ...             yield advertisement
    ...         yield post
    ...
    >>> list(insert_advertisement([1, 2, 3, 4, 5, 6, 7], 'ad', 3))
    [1, 2, 3, 'ad', 4, 5, 6, 'ad', 7]