Hello,
I am trying to write the following python script which removes all shapefiles (any word that ends with .shp) from a list
#Assign variables to the shapefiles
park="Parks_sd.shp"
sewer="Sewer_Main_sd.shp"
water="water"
street="street"
#Create a list of shapefile variables
datalist=[park,sewer,water,street]
# prints the list before the loop to compare the results
print datalist
for x in datalist:
if x.endswith(".shp"):
datalist.remove(x)
print datalist
But the result looks like this
['Parks_sd.shp', 'Sewer_Main_sd.shp', 'water', 'street']
['Sewer_Main_sd.shp', 'water', 'street']
the code succeeds to remove the first item in the list but fails to remove the second one!
What might be the issue here?
Solved! Go to Solution.
You shouldn't be iterating through a list while modifying it. See the following posts:
Python: Removing list element while iterating over list - Stack Overflow
Delete item from list in Python while iterating over it - Stack Overflow
python - Remove items from a list while iterating - Stack Overflow
You can do this instead:
#Assign variables to the shapefiles
sewer="Parks_sd.shp"
park="Sewer_Main.shp"
water="water"
street="street"
#Create a list of shapefile variables
datalist=[park,sewer,water,street]
for x in list(datalist):
if x.endswith(".shp"):
datalist.remove(x)
print(datalist)
You shouldn't be iterating through a list while modifying it. See the following posts:
Python: Removing list element while iterating over list - Stack Overflow
Delete item from list in Python while iterating over it - Stack Overflow
python - Remove items from a list while iterating - Stack Overflow
You can do this instead:
#Assign variables to the shapefiles
sewer="Parks_sd.shp"
park="Sewer_Main.shp"
water="water"
street="street"
#Create a list of shapefile variables
datalist=[park,sewer,water,street]
for x in list(datalist):
if x.endswith(".shp"):
datalist.remove(x)
print(datalist)
Thanks Jonathan, it worked now, this is helpful. By the way why I cannot see " Mark as correct answer" icon next to your answer!