1

I am currently stuck on this error and I did not find a solution (that I understood) on Google:

TypeError: list indices must be integers or slices, not tuple

I try to do:

    for x in values:
        val1 = values[x][0]
        val2 = values[x][1]
        val3 = values[x][2]

        writer.writerow([val1,val2,val3])

values is a nested list. Every nested list has the same length.

I understand the error, but I don't get why I am getting it because if i do: print(values[400][0]), everything works out fine, no error, just the content of the list.

1
  • if you are satisfied with one of the answers, request you to accept one of them as answers. Commented Jan 22, 2021 at 19:22

4 Answers 4

1

When you use for x in values where values is a list, x represent the elements so when you use values[x], you are trying to access the values list by a list index which gives you the error TypeError: list indices must be integers or slices, not tuple.

Try this code:

for x in values:
    val1 = x[0]
    val2 = x[1]
    val3 = x[2]

    writer.writerow([val1,val2,val3])

Or change your code to below to use index based access:

for i in range(len(values)):
    val1 = values[i][0]
    val2 = values[i][1]
    val3 = values[i][2]

    writer.writerow([val1,val2,val3])
Sign up to request clarification or add additional context in comments.

1 Comment

suggesting to use range(len(values)) is not pythonic.
1

By using for x in values, x will be the sublist of you values list. If you try to index your main list by calling values[x], this will throw an error, as you can not index a list using a list. What you want is this

for x in values:
        val1 = x[0]
        val2 = x[1]
        val3 = x[2]

1 Comment

that makes perfect sense, thanks for explaining
1

The issue is with the for loop: you need to write it like so to prevent the error:

for x in range(len(values)):
    val1 = values[x][0]
    val2 = values[x][1]
    val3 = values[x][2]

    writer.writerow([val1,val2,val3])

Better still, use this:

for x in values:
    writer.writerow([x[i] for i in range(3)])

Comments

1

As you mentioned, values is a list of lists.

Example. = [[1,2,3], [3,4,5], [9,10,11]]

So when you do for x in values:, you are taking out each list one by one, so now the x is a simple list. x = [1,2,3] in first iteration.

So, when you do values[x][0], you are doing values[[1,2,3]][0], which doesn't make sense, because list should be indexed with numbers.

Correct code would be

for x in values:
        val1 = x[0]
        val2 = x[1]
        val3 = x[2]
    writer.writerow([val1,val2,val3])

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.