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

For more Practice: Solve these Related Problems:

  • Write a Python program to create groups of k consecutive numbers from a list of numbers.
  • Write a Python program to find all groups of three consecutive numbers that sum to a given value.
  • Write a Python program to extract subsequences of increasing consecutive numbers from a list.
  • Write a Python program to identify all possible sequences of n consecutive numbers in a given 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.