List indices must be integers or slices not tuple python что значит
Перейти к содержимому

List indices must be integers or slices not tuple python что значит

  • автор:

"List indices must be integers or slices, not tuple" error

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 find » + floorsFeature[currentRoom]) . My guess is that there must be something wrong with floors, floorsFeature, and currentRooms. Because I’m a beginner, I’m not sure what the error means. Can someone please explain in simple terms?

Alperen's user avatar

3 Answers 3

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:

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:

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:

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.

list s and tuple s:

Both list s and tuple s 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.

dict s

dict s are a great way of holding state:

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+1 th element (as it starts in 0) of the i+1 th list.

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:

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.

How to Fix TypeError: list indices must be integers or slices, not tuple in Python

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

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:

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

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:

As expected, this now works without errors.

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!

Python error: list indices must be integers or slices, not a tuple

Working with lists and indices can be confusing to new programmers learning Python. When accessing the elements of the list using indices, people often forget that they can only provide integer values to access and end up providing a tuple which causes them to encounter the error in question “Python error: list indices must be integers or slices, not a tuple.”

This post will guide you through the reason why you get this error and how to avoid it as well, and for this, let’s start with a demonstration of the error.

The “Python error: list indices must be integers or slices, not a tuple” Error

To demonstrate this error, create a new list using the following line in Python:

After that, assume that the user wants to access the values at index 1 and 4. Now, the user tries passing both of these index values in the square brackets separated by a comma like this:

The following output is shown on the terminal when the user execute the program:


Let’s see how to fix/avoid this error.

Solution 1: Accessing Separate Elements

If the goal of the user is to access separate elements placed at different index values, then the solution to avoid this error is to use separate bracket notions to access each element. Continuing the above example, to access the values placed at index 1 and index 2, the user can use the following approach:

Executing this code will produce the following output:


With this approach, you have successfully avoided the error.

Solution 2: Accessing a Range of Elements With Indexes

If the goal of the user is to access multiple elements in between certain index values, then instead of passing a tuple, the user can use slices. To use slices, the user needs to place a colon “:” in between the different index values.

Continuing the scenario mentioned above, if the user wants to print the elements between index 1 and 5, then the user can use the following command:

This will show the following output on the terminal:


The output shows the user got the required output without encountering the error.

Conclusion

The error “Python error: list indices must be integers or slices, not a tuple” is caused when the user tries to access the elements of an array but places a comma in between the index values instead of a colon. To avoid this error, the user can access separate elements by using separate bracket notation or provide a range (slice) by using a colon.

About the author

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor’s degree in computer science.

TypeError: List Indices Must Be Integers Or Slices, Not Tuple

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:

Let’s create a second list called b:

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

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:

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

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.

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:

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:

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:

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.

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

Ваш адрес email не будет опубликован. Обязательные поля помечены *