[Tutor] Semantic Error: Trying to access elements of list and append to empty list with for loop

Alex Hall ahall at autodist.com
Thu Jun 2 13:41:23 EDT 2016


Use lst.extend() instead of lst.append() and you should get what you're
after.

On Thu, Jun 2, 2016 at 1:05 PM, Olaoluwa Thomas <thomasolaoluwa at gmail.com>
wrote:

> Hi Tutor,
>
> I'm trying to parse words in a file line by line and place all words into
> another list but I keep getting a list with nested lists.
> I would normally pore over it and go to google and fix my problems but this
> one escapes me and frankly, I'm tired of being stuck in the same place for
> almost a week.
>
> Here's the code:
> fname = raw_input('Enter file name:\n')
> try:
>     fhand = open(fname)
> except:
>     print 'File cannot be found or opened:', fname
>     exit()
> lst = list()
> for line in fhand:
>     words = line.split()
>     #print words (this was a test that a portion of my code was working)
>     lst.append(words)
> print lst
>
> A text file with the following contents
> "But soft
> what light through yonder window breaks
> It is the east and Juliet is the sun
> Arise fair sun and kill the envious moon
> Who is already sick and pale with grief"
>
> would give me the output in the attached screenshot
> [image: Inline image 2]
>
> whereas I want only one list containing strings not nested lists.
>
> Any help would be appreciated.
>
> *Warm regards,*
>
> *Olaoluwa O. Thomas,*
> *+2347068392705*
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Alex Hall
Automatic Distributors, IT department
ahall at autodist.com


More information about the Tutor mailing list