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

Steven D'Aprano steve at pearwood.info
Thu Jun 2 13:44:16 EDT 2016


On Thu, Jun 02, 2016 at 06:05:43PM +0100, Olaoluwa Thomas wrote:

> 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)

If you printed words, you should have seen that it was a list.

If you append a list to a list, what do you get? At the interactive 
prompt, try it:


py> L = [1, 2, 3]
py> L.append([4, 5, 6])
py> L
[1, 2, 3, [4, 5, 6]]


Append takes a single argument, and adds it *unchanged* to the end of 
the list.

What you want is the extend method. It takes a list as argument, and 
appends each item individually:


py> L.extend([7, 8, 9])
py> L
[1, 2, 3, [4, 5, 6], 7, 8, 9]


But if you didn't know about that, you could have done it the 
old-fashioned way:

lst = list()
for line in fhand:
    words = line.split()
    for word in words:
        lst.append(word)



-- 
Steve


More information about the Tutor mailing list