Remove element from list or set if it contains certain character

Andy Hwang :

I am given a txt file of months which I open and fill into a list or set. I need to iterate through the list and remove any months that have the letter 'r' or "R". I tried this using both sets and lists but keep getting a RuntimeError. Here is my code for using a set:

monthList = {}

def main():
    monthList = fillList()
    print(monthList)
    removeRMonths(monthList)

def fillList():
    infile = open("SomeMonths.txt")
    monthList = {line.rstrip() for line in infile}
    return monthList

def removeRMonths(monthList):
    for month in monthList:
        for ch in month:
            if ch == "r" or ch == "R":
                monthList.remove(month)
    print(monthList)

main()

The error I receive is:

Traceback (most recent call last):
  File "/Users/hwang/Desktop/Week7.py", line 115, in <module>
    main()
  File "/Users/hwang/Desktop/Week7.py", line 99, in main
    removeRMonths(monthList)
  File "/Users/hwang/Desktop/Week7.py", line 107, in removeRMonths
    for month in monthList:
RuntimeError: Set changed size during iteration
>>> 

This is my code trying to use a list:

monthList = ()

def main():
    monthList = fillList()
    print(monthList)
    removeRMonths(monthList)

def fillList():
    infile = open("SomeMonths.txt")
    monthList = (line.rstrip() for line in infile)
    return monthList

def removeRMonths(monthList):
    for month in monthList:
        for ch in month:
            if ch == "r" or ch == "R":
                monthList.remove(month)
            else:
                continue
    print(monthList)

main()

My error is:

Traceback (most recent call last):
  File "/Users/hwang/Desktop/Week7.py", line 117, in <module>
    main()
  File "/Users/hwang/Desktop/Week7.py", line 99, in main
    removeRMonths(monthList)
  File "/Users/hwang/Desktop/Week7.py", line 110, in removeRMonths
    monthList.remove(month)
AttributeError: 'generator' object has no attribute 'remove'

What is the reason for these errors? I tried googling each error messages but I couldn't find any answer that I can understand. I am a beginner so I would appreciate an answer that can easily be understood. Thanks in advance!

Barmar :

You shouldn't modify a listor set while you're iterating over it.

Use a list comprehension to create the list in the first place. Then use another list comprehension to filter out the elements. Finally, use slice assignment to update the original list in place after the filtering is done.

monthList = ()

def main():
    monthList = fillList()
    print(monthList)
    removeRMonths(monthList)

def fillList():
    infile = open("SomeMonths.txt")
    monthList = [line.rstrip() for line in infile]
    return monthList

def removeRMonths(monthList):
    monthList[:] = [month for month in monthList if 'r' not in month.lower()]
    print(monthList)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=25634&siteId=1