Itertools Cycle in Python

Level 3124 keystrokes

This cycles through a list infinitely and takes the first 7 elements.

Python code

# cycle() repeats an iterable forever; islice() takes a limited slice of an iterator
1from itertools import cycle, islice
2
# An endless iterator: red, green, blue, red, green, ...
3colors = cycle(["red", "green", "blue"])
# islice(colors, 7) stops after 7 items; list(colors) alone would never finish
4result = list(islice(colors, 7))
# Prints ['red', 'green', 'blue', 'red', 'green', 'blue', 'red']
5print(result)

Output

['red', 'green', 'blue', 'red', 'green', 'blue', 'red']
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 6
  • ,× 4
  • (× 4
  • )× 4
  • =× 2
  • [× 1
  • ]× 1

More Python examples at level 3

← Python typing practice