Groups of five consecutive numbers
Write a Python program to create lists of five consecutive numbers from 1 to 20.
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]
Approach
- Slice
range(1, 21)in steps of 5.
Solution
numbers = list(range(1, 21))print([numbers[i:i + 5] for i in range(0, len(numbers), 5)])[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]
Learn the concept
New to this topic? Read the lesson, then come back.