Reputation: 4850
I'm trying to extract the first few elements of a tab-delimited file using the following:
words = []
name_elements = []
counter = 0
for line in f:
words = line.split()
for element in words:
counter = counter + 1
if words[element].isupper():
name_elements = words[0:counter-1]
print type(counter)
When I run this code, I get this error:
TypeError: list indices must be integers, not str
logout
Even though when I run type(counter) it says it's an integer.
What's the issue?
Upvotes: 0
Views: 530
Reputation: 1123410
You are trying to index words
with element
. element
is a string; it is already the item you wanted to get.
The for
loop is giving you each element from words
in turn, assigning it to the element
variable. element
is not an integer index into the words
list.
Note that your counter is going to go out of bounds; if you want to have an index into the words
list along with the element, use the enumerate()
function. You are also replacing the name_elements
list with a slice from words
; perhaps you wanted to extend the list instead:
for line in f:
words = line.split()
for counter, element in enumerate(words):
if element.isupper():
name_elements.extend(words[:counter-1])
although it is not clear exactly what you wanted to do with the words
list in this case.
Upvotes: 5