w3resource

Python: Generate groups of five consecutive numbers in a list


Generate Groups of Consecutive Numbers

Write a Python program to generate groups of five consecutive numbers in a list.

Python: Generate groups of five consecutive numbers in a list

Sample Solution:

Python Code:

# Create a nested list 'l' using a list comprehension
# This list comprehension generates a 5x5 matrix with elements calculated using the formula 5*i + j
l = [[5*i + j for j in range(1, 6)] for i in range(5)]

# Print the resulting 5x5 matrix 'l'
print(l)

Sample Output:

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]  

Flowchart:

Flowchart: Generate groups of five consecutive numbers in a list

Python Code Editor:

Previous: Write a Python program to split a list into different variables.
Next: Write a Python program to convert a pair of values into a sorted unique array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.