Remove shapefiles from a list

1541
2
Jump to solution
06-27-2017 03:01 PM
AhmadSALEH1
Occasional Contributor III

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?

Tags (2)
0 Kudos
1 Solution

Accepted Solutions
JonathanQuinn
Esri Frequent Contributor

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)

View solution in original post

2 Replies
JonathanQuinn
Esri Frequent Contributor

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)
AhmadSALEH1
Occasional Contributor III

Thanks Jonathan, it worked now, this is helpful. By the way why I cannot see " Mark as correct answer" icon next to your answer!

0 Kudos