List indices must be integers or slices not tuple ошибка python

I am a beginner at coding and I'm currently making an rpg. When I run the code, it gives me the above error. The part that is giving me the error is print("You are on " + floors[currentRoom] + ". You

Lets go by parts:

Provide all the needed code:

We do not know what the foo() function does. It seems to be a validating function but we are missing that part of the code. Please always provide a piece of code we can run to check your errors.

foo() replacement:

To check a choice against a valid set of options you can do it in a single line:

1 in [1, 2, 3] # Output: True
4 in {1, 2, 3} # Output: False
4 not in {1, 2, 3} # Output: True
"b" in ("a", "b", "c") # Output: True
"abc" in ("a", "b", "c") # Output: False
"a" in "abc" # Output: True

As you can see I’ve used different values (int and str) and different containers (list, set, tuple, str, …) and I could use even more. Using not in gives you the opposite answer as expected. In your case you could use:

commands = {'help', 'pokemons', 'bag', 'left', 'right'}
while move not in commands:
    ...

String formating:

There are multiple ways of formatting strings to include variables values inside them, but the most pythonic way is using str.format(). You can check the documentation on how the formatting string works here, but the most simple example would be:

print("Unfortunately, {} doesn't seem to obey or like you...".format(name))

Basically you use placehodlers delimited by {} and then call the .format() function with the arguments you want to place there. Inside the {} you can place different additional strings to format the output as for example determining the number of decimals of a float number.

lists and tuples:

Both lists and tuples in Python are sequence containers. The main difference in that the list is mutable and the tuple isn’t. They are both accessed with the var[position] notation starting from 0. So if you are not going to ever change the content of a sequence, you should use a tuple instead of a list to enforce it to the interpreter and to be more memory efficient. You use parenthesis instead of square brackets for tuples.

dicts

dicts are a great way of holding state:

player = {
          'floor': 1,
          'room': 2,
          'pokemons': [],
          'bag': [],
         }

You don’t have to store the length of an array:

In some languages you always keep the ammount of items inside an array stored. Python’s containers can determine at runtime their size by calling len(container). You have used it at some parts of the code but you are keeping a count and countItems variables that are not needed.

Multi dimensional lists (a.k.a. matrixes):

You seem to be having some problems dealing with matrixes, use the following notation: matrix[i][j] to access the j+1th element (as it starts in 0) of the i+1th list.

matrix = [
          [1, 2, 3],
          [4, 5, 6],
          [7, 8, 9],
         ]
print(matrix[1][2]) # Output: 6

To know the number of lists, in your case floors, use len(matrix). To know the number of elements of the n-th list use len(matrix[n-1]).

The final code:

commands = {'help', 'pokemons', 'bag', 'left', 'right', 'exit'}

gamePlay = True
features = (
            ['nothing here.'                  , 'nothing here.'                            , 'stairs going up.', 'a Squirtle.'       ],
            ['stairs going up and a pokeball.', 'a Charmander.'                            , 'a FIRE!!!'       , 'stairs going down.', 'a pokeball.'],
            ['stairs going down.'             , 'a door covered in vines.'                 , '2 pokeballs!'],
            ['your Bulbasaur!!!'              , 'an Eevee with a key tied around its neck.'],
           )

player = {
          'floor': 1,
          'room': 2,
          'pokemons': [],
          'bag': [],
         }

def positionString(player):
    return "floor {p[floor]} room {p[room]}".format(p=player)

def featureString(player):
    return features[player['floor']-1][player['room']-1]

print("You are finally a Pokemon trainer! Today, you have gotten your very first Pokemon, a Bulbasaur!")
name = input("What will you name your Bulbasaur? ")
print("Unfortunately, {} doesn't seem to obey or like you...".format(name))
print("You try to be friendly to {}, but it just won't listen...".format(name))
print("As {} was busy ignoring you, something seems to catch its attention and it runs off!".format(name))
print("You chase after {}, but it's too fast! You see it running into an abandoned Pokeball Factory.".format(name))
print("You must explore the abandoned Pokeball Factory and find {} before something happens to it!".format(name))
print()
print("You may input 'help' to display the commands.")
print()

while gamePlay == True:
    print("You are on {}. You find {}".format(positionString(player), featureString(player)))
    move = input("What would you like to do? ").lower()
    while move not in commands:
        move = input("There's a time and place for everything, but not now! What would you like to do? ").lower()
    if move == 'left':
        if player['room'] > 1:
            player['room'] -= 1
            print("Moved to {}.".format(positionString(player)))
        else:
            print("*Bumping noise* Looks like you can't go that way...")
    elif move == 'right':
        if player['room'] < len(features[player['floor']-1]):
            player['room'] += 1
            print("Moved to {}.".format(positionString(player)))
        else:
            print("*Bumping noise* Looks like you can't go that way...")
    elif move == 'help':
        print("Input 'right' to move right. Input 'left' to move left. Input 'pokemons' to see what Pokemon are on your team. Input 'bag' to see the items you are carrying. Input 'help' to see the commands again.")
    elif move == 'pokemons':
        if len(player['pokemons']) == 0:
            print("There are no Pokemon on your team.")
        else:
            print("The Pokemon on your team are: {}.".format(", ".join(player['pokemons'])))
    elif move == 'bag':
        if len(player['bag']) == 0:
            print("There are no items in your bag.")
        else:
            print("The items in your bag are: {}.".format(", ".join(player['bag'])))
    elif move == 'exit':
        gamePlay = False
    print()

As you can see I’ve made two functions to get the name of the room and the feature of the room from the state vector so that I do not have to duplicate that part of the code anywhere. One of the function is generating the string itself as they all had the same scheme: floor X room Y. Holding them on a matrix makes no sense unless you wnat to give them names such as 'lobby', I let you the task of modifying the function if thats the case, it should be easy as it would be very similar to the second one. I’ve also added an ‘exit’ command to get out of the loop.

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.

In Python, we index lists with numbers. To access an item from a list, you must refer to its index position using square brackets []. Using a tuple instead of a number as a list index value will raise the error “TypeError: list indices must be integers, not tuple”.

This tutorial will go through the error and an example scenario to learn how to solve it.


Table of contents

  • TypeError: list indices must be integers, not tuple 
    • What is a TypeError?
    • Indexing a List
  • Example #1: List of Lists with no Comma Separator
    • Solution
  • Example #2: Not Using a Colon When Slicing a List
    • Solution
  • Summary

TypeError: list indices must be integers, not tuple 

What is a TypeError?


TypeError
 tells us that we are trying to perform an illegal operation on a Python data object.

Indexing a List

Indexing a list starts from the value 0 and increments by 1 for each subsequent element in the list. Let’s consider a list of pizzas:

pizza_list = ["margherita", "pepperoni", "four cheeses", "ham and pineapple"]

The list has four values. The string “margherita” has an index value of 0, and “pepperoni” has 1. To access items from the list, we need to reference these index values.

print(pizza_list[2])
four cheeses

Our code returns “four cheeses“.

In Python, TypeError occurs when we do an illegal operation for a specific data type.

Tuples are ordered, indexed collections of data. We cannot use a tuple value to access an item from a list because tuples do not correspond to any index value in a list.

You may encounter a similar TypeError to this one called TypeError: list indices must be integers or slices, not str, which occurs when you try to access a list using a string.

The most common sources of this error are defining a list of lists without comma separators and using a comma instead of a colon when slicing a list.

Example #1: List of Lists with no Comma Separator

Let’s explore the error further by writing a program that stores multiples of integers. We will start by defining a list of which stores lists of multiples for the numbers two and three.

multiples = [

    [2, 4, 6, 8, 10]

    [3, 6, 9, 12, 15]

]

We can ask a user to add the first five of multiples of the number four using the input() function:

first = int(input("Enter first multiple of 4"))

second = int(input("Enter second multiple of 4"))

third = int(input("Enter third multiple of 4"))

fourth = int(input("Enter fourth multiple of 4"))

fifth = int(input("Enter fifth multiple of 4"))

Once we have the data from the user, we can append this to our list of multiples by enclosing the values in square brackets and using the append() method.

multiples.append([first, second, third, fourth, fifth])

print(multiples)

If we run this code, we will get the error.”

TypeError                                 Traceback (most recent call last)
      1 multiples = [
      2 [2, 4, 6, 8, 10]
      3 [3, 6, 9, 12, 15]
      4 ]

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

The error occurs because there are no commas between the values in the multiples list. Without commas, Python interprets the second list as the index value for the first list, or:

# List           Index

[2, 4, 6, 8, 10][3, 6, 9, 12, 15]

The second list cannot be an index value for the first list because index values can only be integers. Python interprets the second list as a tuple with multiple comma-separated values.

Solution

To solve this problem, we must separate the lists in our multiples list using a comma:

multiples = [

[2, 4, 6, 8, 10],

[3, 6, 9, 12, 15]

]

first = int(input("Enter first multiple of 4:"))

second = int(input("Enter second multiple of 4:"))

third = int(input("Enter third multiple of 4:"))

fourth = int(input("Enter fourth multiple of 4:"))

fifth = int(input("Enter fifth multiple of 4:"))
multiples.append([first, second, third, fourth, fifth])

print(multiples)

If we run the above code, we will get the following output:

Enter first multiple of 4:4

Enter second multiple of 4:8

Enter third multiple of 4:12

Enter fourth multiple of 4:16

Enter fifth multiple of 4:20

[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]

The code runs successfully. First, the user inputs the first five multiples of four, the program stores that information in a list and appends it to the existing list of multiples. Finally, the code prints out the list of multiples with the new record at the end of the list.

Example #2: Not Using a Colon When Slicing a List

Let’s consider the list of multiples from the previous example. We can use indexing to get the first list in the multiples list.

first_set_of_multiples = multiples[0]

print(first_set_of_multiples)

Running this code will give us the first five multiples of the number two.

[2, 4, 6, 8, 10]

Let’s try to get the first three multiples of two from this list:

print(first_set_of_multiples[0,3])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
1 print(first_set_of_multiples[0,3])

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

The code fails because we pass [0,3] as the index value. Python only accepts integers as indices for lists.

Solution

To solve this problem and access multiple elements from a list, we need to use the correct syntax for slicing. We must use a colon instead of a comma to specify the index values we select.

print(first_set_of_multiples[0:3])
[2, 4, 6]

The code runs successfully, and we get the first three multiples of the number two printed to the console.

Note that when slicing, the last element we access has an index value one less than the index to the right of the colon. We specify 3, and the slice takes elements from 0 to 2. To learn more about slicing, go to the article titled “How to Get a Substring From a String in Python“.

Summary

Congratulations on reading to the end of this tutorial. The Python error “TypeError: list indices must be integers, not tuple” occurs when you specify a tuple value as an index value for a list. This error commonly happens if you define a list of lists without using commas to separate the lists or use a comma instead of a colon when taking a slice from a list. To solve this error, make sure that when you define a list of lists, you separate the lists with commas, and when slicing, ensure you use a colon between the start and end index.

For further reading on the list and tuple data types, go to the article: What is the Difference Between List and Tuple in Python?

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

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 tuple

Code 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.

Estimated reading time: 3 minutes

When working with Python lists in your data analytics projects, when you trying to read the data, a common problem occurs if you have a list of lists, and it is not properly formatted.

In this instance, Python will not be able to read one or more lists and as a result, will throw this error.

In order to understand how this problem occurs, we need to understand how to create a list of lists.

How to create a lists of lists

Let’s look at a simple list:

a = [1,2,3]
print(a)
print(type(a))

Result:
[1, 2, 3]
<class 'list'>

Let’s create a second list called b:

b = [4,5,6]
print(b)
print(type(b))

Result:
[4, 5, 6]
<class 'list'>

So if we want to join the lists together into one list ( hence a list of lists) then:

a = [1,2,3]
b = [4,5,6]

list_of_lists = []
list_of_lists.append(a)
list_of_lists.append(b)
print(list_of_lists)
print(type(list_of_lists))

Result:
[[1, 2, 3], [4, 5, 6]]
<class 'list'>

So as can be seen the two lists are contained within a master list called “list_of_lists”.

So why does the error list indices must be integers or slices, not tuple occur?

Reason 1 ( Missing commas between lists)

If you manually type them in and forget the comma between the lists this will cause your problem:

a=[[1,2,3][4,5,6]]
print(a)

Result (Error):
Traceback (most recent call last):
  line 10, in <module>
    a=[[1,2,3][4,5,6]]
TypeError: list indices must be integers or slices, not tuple

But if you put a comma between the two lists then it returns no error:

a=[[1,2,3],[4,5,6]]
print(a)

Result (no error):
[[1, 2, 3], [4, 5, 6]]
Process finished with exit code 0

Reason 2 ( Comma in the wrong place)

Sometimes you have a list, and you only want to bring back some elements of the list, but not others:

In the below, we are trying to bring back the first two elements of the list.

a= [1,2,3,4,5]
print(a[0:,2])

Result:
Traceback (most recent call last):
   line 14, in <module>
    print(a[0:,2])
TypeError: list indices must be integers or slices, not tuple

The reason that the same error happens is the additional comma in a[0:,2], causes the error to appear as Python does not know how to process it.

This is easily fixed by removing the additional comma as follows:

a= [1,2,3,4,5]
print(a[0:2])

Result:
[1, 2]
Process finished with exit code 0

So why is there a mention of tuples in the error output?

The final piece of the jigsaw needs to understand why there is a reference to a tuple in the error output?

If we return to a looking at a list of lists and look at their index values:

a=[[1,2,3],[4,5,6]]
z = [index for index, value in enumerate(a)]
print(z)

Result:
[0, 1]
Process finished with exit code 0

As can be seen, the index values are 0,1, which is correct.

As before removing the comma gives the error we are trying to solve for:

a=[[1,2,3][4,5,6]]
z = [index for index, value in enumerate(a)]
print(z)

Result:
Traceback (most recent call last):
  line 16, in <module>
    a=[[1,2,3][4,5,6]]
TypeError: list indices must be integers or slices, not tuple

BUT the reference to the tuple comes from the fact that when you pass two arguments (say an index value) a Tuple is created, but in this instance, as the comma is missing the tuple is not created and the error is called.

This stems from the __getitem__ for a list built-in class cannot deal with tuple arguments that are not integers ( i.e. 0,1 like we have returned here) , so the error is thrown, it is looking for the two index values to pass into a tuple.

Понравилась статья? Поделить с друзьями: