1

I'm using readlines method from python to get list of all data lines. Now I wan't to access some index from that list:

file = open('article.txt', 'r')
data = file.readlines()
print data.index(1)
Error: data isn't a list

What's wrong?

3
  • Re-read the error message: It's not "data isn't a list" but rather "x not in list" Commented Dec 6, 2010 at 16:54
  • 1
    BTW, cool that you're currently at exactly 1,337 karma. I dare not upvote your question :) Commented Dec 6, 2010 at 16:57
  • @tim-pietzcker Sorry, I just wasn't near my computer. I always mark questions which help me. Commented Dec 6, 2010 at 17:24

2 Answers 2

5

I think you mean (if your goal is to print the second element of the list):

 print data[1]

data.index(value) returns the list position of value:

>>> data = ["a","b","c"]
>>> data[1]          # Which is the second element of data?
b
>>> data.index("a")  # Which is the position of the element "a"?
0
>>> data.index("d")  # Which is the position of the element "d"? --> not in list!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list
Sign up to request clarification or add additional context in comments.

1 Comment

And if the objective is to print the first line in the input file, use print data[0]
1

Sounds like you mean print data[1] not print data.index(1). See the tutorial

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.