Typeerror list indices must be integers or slices not tuple как исправить

В университете дали задание создать лабиринт, как на картинке (фото), найти кратчайший путь от стартовой точки до финальной.
введите сюда описание изображения
Мой код:

from collections import deque
maze = [
        ['-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','T','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['|','S',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|']
        ['-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-']
        ]


def print_field(field, path = None):
  field = maze.readlines()
n = len(field)
m = len(field[0]) - 1
s = None
t = None
for i in range(n):
  field[i] = field[i].strip()
  if field[i].find('S') !=-1:
    s = (i, field[i].find('S'))
  if field[i].find('T') != -1:
    t = (i, field[i].find('T'))

print_field(field)
print(s,t)

def bfs(field, S, T):
  n = len(field)
  m = len(field[0])
  INF = 10**9
  delta = [(0,-1), (0,1), (1,0), (-1,0)]
  d = [[INF]*m for _ in range(n)]
  p = [[None]*m for _ in range(n)]
  used = [[False]*m for _ in range(n)]
  queue = dequeue()

  d[s[0]][s[1]] = 0
  used[s[0]][s[1]] = True
  queue.append(s)
  while len(queue) != 0:
    x, y = queue.popleft()
    for dx, dy in delta:
      nx, ny = x+dx, y+dy
      if 0 < nx < n and 0 < ny < m and not used[nx][ny] and field[nx][ny] != '#':
        d[nx][ny] = d[x][y] + 1
        p[nx][ny] = (x, y)
        used[nx][ny] = True
        queue.append((nx, ny))
  print(d[t[0]][t[1]])
  cur = t
  path = []
  while cure is not None:
    path.append(cur)
    cur = p[cur[0]][cur[1]]
    path.reverse()
    print_field(field, path[1:-1])

Выдаёт ошибку:

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

Подскажите, пожалуйста, как это исправить?
Возможно, что я представляю вид лабиринта в неправильном формате, что тогда делать?

Буду очень благодарна за помощь!

If you are accessing the list elements in Python, you need to access it using its index position. If you specify a tuple or a list as an index, Python will throw typeerror: list indices must be integers or slices, not tuple.

This article will look at what this error means and how to resolve the typeerror in your code.

Example 1 – 

Let’s consider the below example to reproduce the error.

# Python Accessing List
numbers=[1,2,3,4]
print(numbers[0,3])

Output

Traceback (most recent call last):
  File "c:ProjectsTryoutsmain.py", line 3, in <module>
    print(numbers[0,3])
TypeError: list indices must be integers or slices, not tuple

In the above example, we are passing the [0,3] as the index value to access the list element. Python interpreter will get confused with the comma in between as it treats as a tuple and throws typeerror: list indices must be integers or slices, not tuple.

Solution 

We cannot specify a tuple value to access the item from a list because the tuple doesn’t correspond to an index value in the list. To access a list, you need to use a proper index, and instead of comma use colon : as shown below.

# Python Accessing List
numbers=[1,2,3,4]
print(numbers[0:3])

Output

[1, 2, 3]

Example 2 – 

Another common issue which developers make is while creating the list inside a list. If you look at the above code, there is no comma between the expressions for the items in the outer list, and the Python interpreter throws a TypeError here.

coin_args = [
  ["pennies", '2.5', '50.0', '.01']
  ["nickles", '5.0', '40.0', '.05']
]

print(coin_args[1])

Output

c:ProjectsTryoutsmain.py:2: SyntaxWarning: list indices must be integers or slices, not tuple; perhaps you missed a comma?
  ["pennies", '2.5', '50.0', '.01'] 
Traceback (most recent call last):
  File "c:ProjectsTryoutsmain.py", line 2, in <module>
    ["pennies", '2.5', '50.0', '.01']
TypeError: list indices must be integers or slices, not tuple

Solution

The problem again is that we have forgotten to add the comma between our list elements. To solve this problem, we must separate the lists in our list of lists using a comma, as shown below.

coin_args = [
  ["pennies", '2.5', '50.0', '.01'] ,
  ["nickles", '5.0', '40.0', '.05']
]

print(coin_args[1])

Output

['nickles', '5.0', '40.0', '.05']

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Python Lists

use indexing to store its element in sequential order. In indexing, the list provides a unique sequential integer value to every element, and the index number starts from 0 up to n-1, where n is the total number of elements present in the list.

To access the individual element from a list, we can use the element index number inside the square bracket preceded by the list name. But if we specify a tuple object instead of an index value to access a list element, we will receive the

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

Error.

In this Python debugging tutorial, we will learn what is

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

Error in Python and how to solve it. We will also have a look at a common scenario example where most Python learners commit this mistake.

The Python error

TypeError: list indices must be integers, not tuple

is divided into two statements Error Type and Error Message.

  1. Error Type (


    TypeError


    ): TypeError occurs in Python when we perform an incorrect operation of a Python object type.
  2. Error Message (


    list indices must be integers or slices, not tuple


    ): This error message is telling us that we are using a tuple object instead of a valid index value.


Error Reason

The reason for this error is quite obvious, if you look at the error message, you can clearly tell why this error occurred in your program. Python list index value is always an integer value, even in list slicing, we use index integer value separated with colons.

But if we pass a tuple or values separated by commas as an index value, we will receive the

list indices must be integers or slices, not tuple

Error.


Example

my_list =['a', 'b', 'c', 'd', 'e', 'f']

# access list first element
print(my_list[0,])


Output

Traceback (most recent call last):
File "main.py", line 4, in <module>
print(my_list[0,])
TypeError: list indices must be integers or slices, not tuple


Break the code

We are receiving the error in our above program because at line 4, we have passed a tuple as an index value to access the first element of

my_list

object.

The Python interpreter read the comma-separated values as a tuple. That’s why in line 4, where we are printing the

my_list

first, the element using the index value

0,

.

Python treated the

0,

statement as a tuple and threw the error because the index value must be an integer, not a tuple.


Solution

To solve the above program, we just need to remove the comma after

0

and it will be treated as an integer object.

my_list =['a', 'b', 'c', 'd', 'e', 'f']

# access list first element
print(my_list[0])


Output

a


A Common Scenario

The most common scenario where many Python learners encounter this error is when they use commas

,

by mistake for list slicing instead of a colon

:

.


Example

Let’s say we want to access the first four elements from our list, and for that list, slicing would be a perfect choice. Using list slicing, we can access a sequential part of the list using a single statement.

my_list =['a', 'b', 'c', 'd', 'e', 'f']

# access first 3 elements
print(my_list[0,4])


Output

Traceback (most recent call last):
File "main.py", line 4, in <module>
print(my_list[0,4])
TypeError: list indices must be integers or slices, not tuple


Break the code

In the above example, we tried to perform Python list slicing on our list object

my_list

to access its first 3 elements. But in line 4, instead of a colon

:

we used commas to specify the start

0

and end

4

indices for the list slicing.

Python interpreter read the

1,4

statement as a tuple and return the TypeError


list indices must be integers or slices, not tuple


.


Solution

The solution for the above problem is very simple. All we need to do is follow the correct Python list slicing syntax that is as follows:

list_name[start_index : end_index : steps]


Example

my_list =['a', 'b', 'c', 'd', 'e', 'f']

# access first 3 elements
print(my_list[0:4])


Output

['a', 'b', 'c', 'd']


Final Thoughts!

In this Python tutorial, we learned about

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

Error and how to solve it. This error raises in Python when we use a tuple object instead of the integer index value to access an element from a Python list.

To solve this problem, you need to make sure that the error list element you are using must be accessed through a proper index value, not a tuple.

If you are still getting this error in your python program, you can share your code in the comment section with the query, and we will help you to debug it.


People are also reading:

  • Online Python Compiler

  • Python ValueError: invalid literal for int() with base 10: Solution

  • Python XML Parser Tutorial

  • Python TypeError: ‘float’ object is not callable Solution

  • np.arange() | NumPy Arange Function in Python

  • Python indexerror: list assignment index out of range Solution

  • Python Internet Access

  • Python typeerror: ‘list’ object is not callable Solution

  • Python String count()

  • Python TypeError: can only concatenate str (not “int”) to str Solution

Are you looking for a way to fix “TypeError: list indices must be integers or slices not tuple” error?

Python TypeError is the exception that indicates the invalid usage of an object type in an operation. The error usually occurs if an operation is performed on an object that does not support the operation itself, or an object of incorrect type. For example, TypeError is raised every time you try to concatenate an integer with a string.

In this article, we will dig deep into the “TypeError: list indices must be integers or slices not tuple” error and how beginners can debug and fix it quickly and effectively.

“TypeError: list indices must be integers or slices not tuple” indicates that you’re accessing a Python list using a tuple instead of an index or an index range. The “list indices” in the error message simply means “list indexes”.

Python beginners often mixed the slice syntax (using colons) with the list syntax (using commas).

Another common thing that cause this type of error is accessing a non-nested list using multi-dimensional slicing.

In order to fix the error, make sure you’re using the right syntax with the right object. Let’s see some examples:

# TypeError: list indices must be integers or slices, not tuple
# because of missing comma
a_list = [['a', 'b', 'c']['a1', 'b1', 'c1']] Code language: Python (python)

In the example above, we forgot to add a comma when we’re trying to define a nested list, so Python mistakenly recognize it as we’re trying to access a list using indexes, hence display a TypeError.

Find the tuple indexes

There is a chance you may have used a tuple to access a list in a straightforward way, which triggers “TypeError: list indices must be integers or slices not tuple” error. Typically, such source code may look like below (oversimplified example).

a_list = ['a', 'b', 'c', 'd', 'e']
indexes = 0, 1 
result = my_list[my_tuple]Code language: Python (python)

In real life, the indexes may be the result of another operation, or the result from a function. In Python, typically a tuple is created by wrapping several objects in a parentheses pair (). For example: ('a', 'b') or ('a', 'b', 'c', 'd'). The parentheses are optional, which means 'a', 'b', 'c', 'd' also creates a tuple as well. In addition to that, you can also create a tuple using one of the following ways :

  • A pair of parentheses () creates an empty tuple
  • 0, or ('a',) also creates a tuple
  • Explicitly using tuple() constructor. For example, `tuple(‘a’, ‘b’).

With that many ways to create a tuple, follow the suggestions below to debug your program:

  • Use the type class to inspect the type of each object.
  • Alternatively, use isinstance to check whether the in object is an instance or a subclass of a class or not.

Check your syntax

In this case, simply inspect and add commas to the list definition accordingly.

# a_list definition with the proper syntax
a_list = [['a', 'b', 'c'],['a1', 'b1', 'c1']] Code language: Python (python)

Another common scenario is using an incorrect index accessor.

a_list = [['a', 'b', 'c'],['a1', 'b1', 'c1']] 
result = a_list[0, 0]
# Will cause TypeError: list indices must be integers or slices, not tupleCode language: Python (python)

In the example, we two integer separated by a comma to get an element from a nested list. This is the wrong syntax, which causes Python interpreter to mistakenly recognize it as a tuple.

If you’re trying to access an element from a nested list, you would have to use two pair of square brackets to do it. The first bracket pair will return the first element, then the second one will be the index to the element you just got.

a_list = [['a', 'b', 'c'],['a1', 'b1', 'c1']] 
result = a_list[0][0]
# "result" will be 'a'
# This equals to
result1 = a_list[0] # Returns ['a', 'b', 'c']
result2 = result1[0] # Returns 'a'Code language: Python (python)

In case you want to get a part of the list in Python, use the slicing syntax as follows:

a_list = ['a', 'b', 'c', 'd', 'e', 'f']
print(a_list[0:3]) # returns ['a', 'b', 'c']
print(a_list[:3]) # returns ['a', 'b', 'c']
print(a_list[3:]) # returns ['d', 'e', 'f']Code language: Python (python)

Here we use the colon to separate the start and end indexes. Both the start and end index are optional. If not specified, the value for start index would be 0 and end index would be defaulted to the length of the list.

How to access multiple, unrelated list items without slicing? Simple, just use an index to access them separately and concatenate them afterwards.

a_list = ['a', 'b', 'c', 'd', 'e', 'f']
print([a_list[0], a_list[2], a_list[4]]) # returns ['a', 'c', 'e']Code language: Python (python)

The code doesn’t look very elegant, but it does the job without having to use an external library. Another way to do it is using a for loop like below :

a_list = ['a', 'b', 'c', 'd', 'e', 'f']
indexes = [0,2,4]
result = [a_list[x] for x in indexes]
print(result) # returns ['a', 'c', 'e']Code language: Python (python)

We hope that the article helped you successfully debug and fix “TypeError: list indices must be integers or slices not tuple” error in Python, as well as avoid encountering it in the future. We’ve also written a few other guides for fixing common Python errors, such as Fix “Max retries exceeded with URL” ,Python Unresolved Import in VSCode or “IndexError: List Index Out of Range” in Python.
If you have any suggestion, please feel free to leave a comment below.

When you’re working in Python, especially with lists and tuples, you might come across this error:

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

This error is caused by the fact that you’re trying to access a list element by a tuple.

In this post, we’ll look and some example code that causes this error and how to fix it.

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

Before we learn how to fix it, let’s look at some example code that causes this error:

	locations = [
    ["New York", "USA"]
    ["Paris", "France"]
]

london = ["London", "UK"]

locations.append(london)

print(locations)

Depending on your compiler, you might even already get the solution to this problem:

	<string>:2: SyntaxWarning: list indices must be integers or slices, not tuple; perhaps you missed a comma?
Traceback (most recent call last):
File "<string>", line 2, in <module>
TypeError: list indices must be integers or slices, not tuple

It says it on the first line of this error, that perhaps you missed a comma, and indeed we did.

By defining locations without a comma, we’re creating a list of lists, instead of a list of tuples.

That distinction is the root of the problem.

All we need to do is add a comma so that the compiler understands that this is a list of tuples:

	locations = [
    ["New York", "USA"],
    ["Paris", "France"]
]

london = ["London", "UK"]

locations.append(london)

print(locations)

As expected, this now works without errors.

	[['New York', 'USA'], ['Paris', 'France'], ['London', 'UK']]

Conclusion

In this post, we learned how to fix the problem of TypeError: list indices must be integers or slices, not tuple.

Simply ensure that you are using a list of tuples, instead of a list of lists, which can be done by adding a comma to separate the different tuples.

Thanks for reading!

If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!

  • Support Us

  • Join

  • Share

  • Tweet

  • Share

Give feedback on this page!

Добавить комментарий