I made a simpler version of the code I’m working on below. When I print the biglist list at the bottom of the code, I expected to see 10 iterations of the same data in the list:
new_result = True
countlist = 0
countlist2 = 2
countlist3 = 3
biglist = []
while new_result:
if countlist == 10:
new_result = False
else:
new_result = True
while countlist2 < 100:
timestwo = countlist2 * 2
countlist2 += 2
timesthree = countlist3 * 3
countlist3 += 3
biglist.append([timestwo,timesthree])
countlist += 1
countlist2 = 2
countlist3 = 3
print(biglist)
My questions are:
-
Can someone explain to me why only 1 iteration of the numbers data is showing in the list?
-
Where in the code does the list get wiped out again?
-
Is there a way to just add the list to the list of lists to get 10 iterations of the data?
Data Returned:
[[4, 9], [8, 18], [12, 27], [16, 36], [20, 45], [24, 54], [28, 63], [32, 72], [36, 81], [40, 90], [44, 99], [48, 108], [52, 117], [56, 126], [60, 135], [64, 144], [68, 153], [72, 162], [76, 171], [80, 180], [84, 189], [88, 198], [92, 207], [96, 216], [100, 225], [104, 234], [108, 243], [112, 252], [116, 261], [120, 270], [124, 279], [128, 288], [132, 297], [136, 306], [140, 315], [144, 324], [148, 333], [152, 342], [156, 351], [160, 360], [164, 369], [168, 378], [172, 387], [176, 396], [180, 405], [184, 414], [188, 423], [192, 432], [196, 441]]
Expected 10 iterations of the same data in the list, instead I only got 1 iteration.
>Solution :
Current problem
After the first iteration of the outer while loop, you keep incrementing countlist2 until the condition of the inner while loop stops from holding. At the next iteration (and all subsequent iterations) of the outer while loop, the condition will not hold to begin with and the inner while loop will not execute.
Solution
Initiate the relevant variables inside the loop:
new_result = True
countlist = 0
biglist = []
while new_result:
if countlist == 10:
new_result = False
else:
new_result = True
countlist2 = 2
countlist3 = 3
while countlist2 < 100:
timestwo = countlist2 * 2
countlist2 += 2
timesthree = countlist3 * 3
countlist3 += 3
biglist.append([timestwo,timesthree])
countlist += 1
print(biglist)
Improvements
To avoid such problems, use for loops when the range of iteration is pre-determined:
biglist = []
for _ in range(10):
countlist3 = 3
for countlist2 in range(2, 100, 2):
timestwo = countlist2 * 2
timesthree = countlist3 * 3
countlist3 += 3
biglist.append([timestwo,timesthree])
print(biglist)
Or using zip:
biglist = []
for _ in range(10):
for i, j in zip(range(2, 100, 2), range(3, 100, 3)):
timestwo = i * 2
timesthree = j * 3
biglist.append([timestwo,timesthree])
print(biglist)