Python - Convert List to custom overlapping nested list

PythonServer Side ProgrammingProgramming

When it is required to convert a list to a customized overlapping nested list, an iteration along with the ‘append’ method can be used.

Example

Below is a demonstration of the same

my_list = [31, 25, 36, 76, 73, 89, 91, 100]
print("The list is :")
print(my_list)

my_step, my_size = 3, 4

my_result = []

for index in range(0, len(my_list), my_step):
   my_result.append(my_list[index: index + my_size])

print("The result is :")
print(my_result)

Output

The list is :
[31, 25, 36, 76, 73, 89, 91, 100]
The result is :
[[31, 25, 36, 76], [76, 73, 89, 91], [91, 100]]

Explanation

  • A list is defined and is displayed on the console.

  • Two integers are defined.

  • An empty list is defined.

  • The original list is iterated over, and the element at a specific index is appended to the empty list.

  • This list is the result which is displayed as output on the console.

raja
Published on 15-Sep-2021 12:01:53
Advertisements