Iterating through a Python list and filtering out numbers manifest to unsatisfactory results

# Initialize a list with variable strings, integers, and floats

x = ["678", "19.99", "132.1", "swim", "40203", "apple", "building"]

# Iterate through the list using a for loop
for each_value in x:
     print(each_value.isalpha())
     if each_value.isalpha() == False:
          x.remove(each_value)

# Display List in 2 formats
print(x)

for each_value in x:
    print(each_value)

My intention is to remove all the strings that contain numbers from the list.

In this screenshot, you can see that it isn’t iterating through each value. And based on the printed each_value.isalpha() statement, it’s only giving results to every other value.

enter image description here

Your help is well appreciated. Thanks for giving me the opportunity to learn!

>Solution :

You do not want to iterate through a list and modify it at the same time. Instead, you can create a results list while iterating through x:

# Initialize a list with variable strings, integers, and floats
x = ["678", "19.99", "132.1", "swim", "40203", "apple", "building"]

# Instantiate results list
results = []
# Iterate through x
for each_value in x:
    # Append value to results if isalpha()
    if each_value.isalpha():
        results.append(each_value)

results:

['swim', 'apple', 'building']

Here is a quoted answer from the question Modifying list while iterating as of why to use a secondary list:

The general rule of thumb is that you don’t modify a
collection/array/list while iterating over it.

Use a secondary list to store the items you want to act upon and
execute that logic in a loop after your initial loop.

Leave a Reply