cage4313
cage4313

Reputation: 1

how to fix "list indices must be integers, not list"

Hi i would like to know what is wrong with this code

f = open('test.txt', 'a+')
yourResult = [line.split(',') for line in f.readlines()]
for answer in yourResult:
    print (yourResult[answer])

a = raw_input('What Was That')
Format = (answer + ' : ' + a + ', ')
f.write(Format)
print (Format)
File = open('test.txt', 'r')

Upvotes: 0

Views: 1055

Answers (4)

scotty3785
scotty3785

Reputation: 7006

You don't need to use

print(yourResult[answer])

using

print(answer)

will do what I expect you want. Since you have created yourResult as a list, yourResult[x] expects x to be a number from 0 to len(yourResult)-1. By doing

for answer in yourResult

You are iteratively setting answer to each item in yourResult.

Upvotes: 0

pwnsauce
pwnsauce

Reputation: 414

yourResult[answer] can't work, the [] are expecting integer. when you do:

for answer in yourResult:, answer is a list(thanks bruno desthuilliers).

You should do:

for answer in yourResult:
    print (answer)

here, answer will be yourResult[0], then yourResult[1] etc..

Upvotes: 1

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Python's for loop doesn't yield indices but the item in the sequence itself, so here, inside the loop, answer is already an element of yourResult. IOW, you want:

for answer in yourResult:
    print (answer)

As a side note:

1/ a file object is an iterable, so you don't need to use readlines(), you can (and should) directly iterate over the file (it will avoid loading the whole content in memory):

2/ open() is context manager which takes care of properly closing the file.

The clean version of your code would then be:

with open('test.txt', 'r') as f:
    yourResult = [line.split(',') for line in f]

for answer in yourResult:
    print(answer)

Upvotes: 1

HolyDanna
HolyDanna

Reputation: 629

When you use a for this way, answer is one of the elements of yourResult, not the index of such an element.
To do what you want with indexes, do :

for answer in range(len(yourResult)):
    print(yourResult[answer])

In this case, you'll look inside yourResult by using indexes.

If not, you can do :

for answer in yourResult:
    print(answer)

In this case, you loop directly at the elements inside the array, thus not needing to access them through indexes.

Upvotes: 0

Related Questions