Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading