Reputation: 9243
I have an list and would like to loop through each row and print the value from column 1. I am getting the error message TypeError: list indices must be integers, not list
What am I missing here?
test = [[1,2,4],[3,4,3]]
for currentrow in test:
print test[currentrow][1]
Upvotes: 0
Views: 101
Reputation: 3503
If you are trying to access second element in each of the arrays in the test this what you would do:
test = [[1,2,4],[3,4,3]]
for currentrow in test:
print currentrow[1]
Upvotes: 1
Reputation: 11253
When you use a for loop in Python, the variable currentrow
will be assigned the actual object in the list, not the index. So, what you want is the following:
test = [[1,2,4],[3,4,3]]
for currentrow in test:
print currentrow[1]
A benefit of this approach is that it's a bit easier to read as well.
If you'd like the index to be available in the loop body, you can use enumerate
. Here's an example:
test = [[1,2,4],[3,4,3]]
for i, currentrow in enumerate(test):
print "Row {}: {}".format(i, currentrow[1])
Upvotes: 1
Reputation: 756
The issue with your code here is that when you loop through your test
list, each entry is a list of its own. As such, you're trying to use that entry as an index, which is not possible. Try something like this:
for i in range(len(test)):
print test[i][1]
Upvotes: 0
Reputation: 1220
In your example, currentrow
will be a list.
So what you want to do is
test = [[1,2,4],[3,4,3]]
for currentrow in test:
print currentrow[1]
will print
2
4
Upvotes: 2