Python for loop not iterating

Python for loop not iterating

Each time your first loop runs, it sets linelist to a new value, overwriting any old value. After that first loop runs, linelist will contain only the split result from the last line of the file. Every time you process one line of the file, you are throwing away whatever you did with the previous line.

If you want to build a list of all words in the dictionary file, you need to make a list and append to it on each iteration of your for line in infile loop.

Also, it doesnt make much sense to use split on each line if each line is just one word, since there will be no splitting to be done.

for line in infile:
    line = line.strip()
    linelist = line.split( )

Every time you do linelist = line.split( ), that replaces the old linelist with words from just the last line. The list ends up only holding words from the last line. If you want words from the entire file, create a single linelist and extend it with new words:

linelist = []
for line in infile:
    # split with no argument splits on any run of whitespace, trimming
    # leading and trailing whitespace
    linelist += line.split()
#            ^ this means add the elements of line.split() to linelist

Since apparently every word is on its own line, though, you shouldnt even be using split:

words = [line.strip() for line in infile]

Python for loop not iterating

Your second loop is not indented, so you run it only on the last value of linelist.

Leave a Reply

Your email address will not be published. Required fields are marked *