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!