Print values from list based from separate text file
<p>How do I print a list of words from a separate text file? I want to print all the words unless the word has a length of 4 characters.  </p>

<p>words.txt file looks like this:</p>

<p>abate  chicanery   disseminate gainsay latent  aberrant    coagulate   dissolution garrulous   laud</p>

<p>It has 334 total words in it. I'm trying to display the list until it reaches a word with a length of 4 and stops. </p>

<pre><code>wordsFile = open("words.txt", 'r')
words = wordsFile.read()
wordsFile.close()
wordList = words.split()

#List outputs length of words in list

lengths= [len(i) for i in wordList]
for i in range(10):
    if i &gt;= len(lengths):
         break
    print(lengths[i], end = ' ')

# While loop displays names based on length of words in list

while words != 4:
    if words in wordList:
        print("\nSelected words are:", words)
    break
</code></pre>

<h1>output</h1>

<pre><code>5 9 11 7 6 8 9 11 9 4
</code></pre>

<h1>sample desired output</h1>

<p>Selected words are:</p>

<p>Abate </p>

<p>Chicanery </p>

<p>disseminate </p>

<p>gainsay </p>

<p>latent  </p>

<p>aberrant    </p>

<p>coagulate   </p>

<p>dissolution </p>

<p>garrulous   </p>

<p>While i'd use a for or a while loop, like Paul Rooney suggested, you can also adapt your code.
When you create the list lengths[], you create a list with ALL the lengths of the words contained in wordList.</p>

<p>You then cycle the first 10 lengths in lengths[] with the for loop;
If you need to use this method, you can nest a for loop, comparing words and lengths:</p>

<pre><code>#lengths[] contains all the lengths of the words in wordList
lengths= [len(i) for i in wordList]
#foo[] cointains all the words in wordList
foo = [i for i in wordList]

#for the first 10 elements of lengths, if the elements isn't 4 char long
#print foo[] element with same index
for i in range(10):
    if lengths[i] != 4:
        print(foo[i])
    if i &gt;= len(lengths):
        break
</code></pre>

<p>I hope this is clear and it's the answer you were looking for</p>

python python-3.x