I have a list data type. For example, list_example=[1,2,3,4] I want to delete all its contents using a for loop

The code I wrote is:

 list_example=[1,2,3,4] for i in range(0,len(list_example)): del list_example[i] i-=1 

But the problem is that the variable 'i' does not seem to be changed in this cycle ...

  • Learn about code indenting in Python ;-) - Kromster pm

2 answers 2

Changes to the variable i inside the loop have no meaning, since at the next iteration, the next element obtained from the range will be taken as i .

Therefore, it does not matter whether you decrease by one at the end of each iteration i , nullify it, or even decrease it by a million. Anyway, at the beginning of the iteration, i will take the next value from the series 0, 1, 2, 3 .

    Do you understand that by deleting a value from the list, you decrease it? Therefore, with the range parameter specified in the for loop, you will always see an error with the index. If you already want to use the function del, then try to go through the list not from the beginning to the end, but vice versa:

     list_example=[1,2,3,4] for i in range(len(list_example)-1, -1, -1): del list_example[i] print(i) print(list_example) 

    We get:

     3 2 1 0 [] 
    • But the question is not about that at all. The author cannot understand why at the end of each iteration he reduces i by one, but this does not affect anything. - Xander