I am learning to write a guardian pattern to prevent empty lists from breaking my code below. I purposely placed a blank line in the txt file to test the guardian pattern.
han = open('file.txt')
for line in han:
line = line.rstrip()
wds = line.split(',')
print(len(wds)) # this is what i used to test the blank line - confirmed this does NOT return 0
if len(wds) < 1: continue # << This is my guardian pattern
#if line == '' :
# continue
if wds[5] != 'random string' :
continue
print(wds[1])
When I test the len() function directly in the Python shell, it has no problem returning 0 when I input a blank list in the parameter.
However, with my code above, when I use the len() function and insert the blank list 'wds', it seems like len() does not return the 0 and completely skips my guardian pattern which leads to the traceback you would expect if a guardian pattern was not there:
File "C:\Users\user\Documents>DataStructures_Pt2.py", line 16, in <module>
if wds[5] != 'random string' :
IndexError: list index out of range
Notice the print() statement before my guardian statement. All lines before my blank line are returning a value. The only line that does not return a value is the blank line. Full output below
C:\Users\User\Documents>DataStructures_Pt2.py
6
6
6
6
6
6
6
6
6
9
6
6
6
6
6
6
6
6
6
6
6
6
6
6
1
Traceback (most recent call last):
File "C:\Users\user\Documents>DataStructures_Pt2.py", line 16, in <module>
if wds[5] != 'random string' :
IndexError: list index out of range