Sublists from a python list such that first sublist contains first 2 elements of list, then first 3 elements and so on and Num as 3rd, 4th and so on
Question:
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".........................................................")
Desired Output:
list2 = [1, 3] Num = 2
list2 = [1, 3, 2] Num = 10
list2 = [1, 3, 2, 10] Num = 4
list2 = [1, 3, 2, 10, 4] Num = 8
list2 = [1, 3, 2, 10, 4, 8] Num = 6
Answers:
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.
a = [1, 3, 2, 10, 4, 8, 6]
for i in range(2,len(a)):
print(f'list2 = {a[:i]} Num={a[i]}')
Output
list2 = [1, 3] Num=2
list2 = [1, 3, 2] Num=10
list2 = [1, 3, 2, 10] Num=4
list2 = [1, 3, 2, 10, 4] Num=8
list2 = [1, 3, 2, 10, 4, 8] Num=6
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".........................................................")
Desired Output:
list2 = [1, 3] Num = 2
list2 = [1, 3, 2] Num = 10
list2 = [1, 3, 2, 10] Num = 4
list2 = [1, 3, 2, 10, 4] Num = 8
list2 = [1, 3, 2, 10, 4, 8] Num = 6
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.
a = [1, 3, 2, 10, 4, 8, 6]
for i in range(2,len(a)):
print(f'list2 = {a[:i]} Num={a[i]}')
Output
list2 = [1, 3] Num=2
list2 = [1, 3, 2] Num=10
list2 = [1, 3, 2, 10] Num=4
list2 = [1, 3, 2, 10, 4] Num=8
list2 = [1, 3, 2, 10, 4, 8] Num=6