Python | Incremental section of a slice in a list

Method # 1: Using Loops
This is a brute force method by which this task can be accomplished. We just manually count and increment the counter with each iteration to slice and create a dictionary key.

# Python3 code to demonstrate how it works
# Incremental slice section in list
# Using a loop

 
# initializing list

test_list = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]

 
# print original list

print ( "The original list is:" + str (test_list))

 
# Incremental slice section in the list
# Using a loop

res = {}

N = 1

strt = 0

while strt & lt;  len (test_list):

res [N] = test_list [strt: strt + N]

strt + = N

N + = 1

  
# print result

print ( "The partitioned dictionary from list is:" + str (res) )

Output:

The original list is: [1, 2, 3, 4, 5, 6, 7 , 8, 9, 10]
The partitioned dictionary from list is: {1: [1], 2: [2, 3], 3: [4, 5, 6], 4: [7, 8, 9, 10]}

Method # 2: Using enumerate () + slice () + next () + iter () + count ()
A combination of the above functions can be used to accomplish this task. In this, next () is used to iterate through the list converted to an iterator using iter () slice () slices the list. Count () helps in managing the count, and the enumeration keeps track of the element and the indices in the list.

# Python3 code to demonstrate how it works
# Incremental slice section in list
# Using enumerate () + slice () + next () + iter () + count ()

from itertools import islice, count

 
# initializing list

test_list = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]

 
# printing the original list

print ( "The original list is:" + str (test_list))

 
# Incremental slice section in the list
# Using enumerate () + slice () + next () + iter () + count ()

res < / code> = {key: val for key, val in enumerate ( iter ( lambda i = iter (test_list),

c = count ( 1 ): list (islice (i, next (c))), []), 1 )}

  
# print result

print ( "The partitioned dictionary from list is:" + str (res))

Output:

The original list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The partitioned dictionary from list is: {1: [1], 2: [2, 3], 3: [4, 5, 6], 4: [7, 8 , 9, 10]}