Working with lists and indices might be complicated to new programmers studying Python. When accessing the weather of the record utilizing indices, individuals typically overlook that they’ll solely present integer values to entry and find yourself offering a tuple which causes them to come across the error in query “Python error: record indices should be integers or slices, not a tuple.”
This submit will information you thru the explanation why you get this error and the best way to keep away from it as properly, and for this, let’s begin with an indication of the error.
The “Python error: record indices should be integers or slices, not a tuple” Error
To show this error, create a brand new record utilizing the next line in Python:
numbers = [123,76,23,95,12,66]
After that, assume that the consumer desires to entry the values at index 1 and 4. Now, the consumer tries passing each of those index values within the sq. brackets separated by a comma like this:
The next output is proven on the terminal when the consumer execute this system:
Let’s see the best way to repair/keep away from this error.
Resolution 1: Accessing Separate Components
If the objective of the consumer is to entry separate components positioned at totally different index values, then the answer to keep away from this error is to make use of separate bracket notions to entry every component. Persevering with the above instance, to entry the values positioned at index 1 and index 2, the consumer can use the next method:
print(numbers[1], numbers[4])
Executing this code will produce the next output:
With this method, you could have efficiently averted the error.
Resolution 2: Accessing a Vary of Components With Indexes
If the objective of the consumer is to entry a number of components in between sure index values, then as an alternative of passing a tuple, the consumer can use slices. To make use of slices, the consumer wants to put a colon “:” in between the totally different index values.
Persevering with the state of affairs talked about above, if the consumer desires to print the weather between index 1 and 5, then the consumer can use the next command:
This can present the next output on the terminal:
The output reveals the consumer obtained the required output with out encountering the error.
Conclusion
The error “Python error: record indices should be integers or slices, not a tuple” is prompted when the consumer tries to entry the weather of an array however locations a comma in between the index values as an alternative of a colon. To keep away from this error, the consumer can entry separate components through the use of separate bracket notation or present a spread (slice) through the use of a colon.