Deleting elements from list not results as expected [duplicate]

46
December 10, 2019, at 11:40 PM
This question already has answers here:
How to remove items from a list while iterating? (30 answers)
strange result when removing item from a list [duplicate] (4 answers)
Closed 13 hours ago.

I'm new to python, just exploring list in python.

I'm facing a weird problem, see the below code.

my_list = [i for i in range(10)]  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for a_item in my_list:
    if a_item > 5:
        my_list.remove(a_item)
print my_list

First, I'm creating a list of integers (0 to 9).

In the loop, I'm iterating over the elements and deleting element if its greater than 5.

So, in the end, I'm expecting the result as the list containing elements from 0 to 5. but in actual I'm getting [0, 1, 2, 3, 4, 5, 7, 9]

Can somebody please explain why am I getting such a result.

Thank you in advance!

READ ALSO
Parsing table to csv Python

Parsing table to csv Python

I need to parse table from https://egehse

55
pserve not working inside docker container

pserve not working inside docker container

I am trying to develop pyramid application with using docker-containerI build a docker images with below docker file

70
Download multiple files in Django without creating zip

Download multiple files in Django without creating zip

Is there a way to download multiple files in Django without creating zipfile on single click/requestFor downloading single file I am using the following code in views

39