From a given list, I have to create sublists that follow a sequence as first 2 elements, then first 3 elements, then first 4 elements and so on from the given list and corresponding num as 3rd element, 4th element, 5th element, and so on. Used the below-given code, but it is not giving the 0 indexed list element i.e. 1. What's wrong?
list = [1, 3, 2, 10, 4, 8, 6]
list2 = []
Num = None
for i in range(2,len(list)):
print(f"i = {i}")
Num = list[i]
for j in range(0,i):
print(f"j = {j}")
list2.append(list[j])
print(f"\tlist2 = {list2}\tNum = {Num}")
print(f".........................................................")
CodePudding user response:
try changing
for i in range(2,len(list)):
condition to
for i in range(1,len(list)):
so the loop would start on the first element of the given list. This should solve the problem.
CodePudding user response:
a = [1, 3, 2, 10, 4, 8, 6]
data = []
for i in range(2,len(a)):
data.append(a[:i])
print(data)
Output
[[1, 3], [1, 3, 2], [1, 3, 2, 10], [1, 3, 2, 10, 4], [1, 3, 2, 10, 4, 8]]