Python - slice a generator object


Python tip:

You can use itertools.islice to use only part of a generator.

👇

from itertools import cycle, islice

chord_sequence = cycle(["G", "D", "e", "C"])

song_chords = [chord for chord in islice(chord_sequence, 16)]

print(song_chords)
"""
['G', 'D', 'e', 'C', 'G', 'D', 'e', 'C', 'G', 'D', 'e', 'C', 'G', 'D', 'e', 'C']
"""