0

I am making a program that deletes every third element of a list starting at the element[2]. Towards the end of this for loop, the program stops prematurely.

import random

inputrange = int(input('How many numbers do you want in the list?'))
intmax = int(input('What is the largest possible integer in the list?'))
intmin = int(input('What is the smallest possible integer in the list'))

rand = [random.randint(intmin,intmax) for i in range(inputrange)]


for i in rand:
    del rand[2::3]
    print(rand[2::3])
    print(rand)

print(rand)

In a list starting with 100 elements (just an example), I end up with 7 elements in rand. Why? The program should continue del rand[2::3] until there are no more elements to allow for a deletion. With 7 elements remaining given the aforementioned 100 elements to begin, the loop should run 4 more times until only rand[0] and rand[1] exist. However I am left with rand[0, 6]

1 Answers1

0

I did not understand your question well, but I will explain what happens to your code.

Its loop is based on the modified list in each iteration, that is, it will become smaller each time. Take as an example the case where your list has 14 elements as shown below:

[631, 485, 571, 268, 407, 318, 610, 297, 132, 159, 525, 183, 667,230]

in the first iteration of the loop i = 631 and elements 571,318,132,183 are deleted from the list with the following list remaining.

[631, 485, 268, 407, 610, 297, 159, 525, 667, 230]

and the second iteration of the loop i will be equal to the second value of the list 485. The values ​​268, 297, 667 will be removed by subtracting:

[631, 485, 407, 610, 159, 525, 230]

i now has value of the third element 407. repeating the process would have:

[631, 485, 610, 159, 230]

i = 159
[631, 485, 159, 230]

at this point i would have the value of the fifth element that does not exist. then the loop is closed.

to solve your problem you can use the initial size of the list as in the code below

for i in range (len (rand)):
    of the rand [2 :: 3]

or what I recommend is to use the while loop:

while len (rand)> 2:
    of the rand [2 :: 3]

I hope you have solved your doubts. thank you.

Lucas Costa
  • 99
  • 11