Tuple indices must be integers or slices not str ошибка

It’s really late but OP’s problem can be averted by unpacking the tuples in result in the for statement as the result is iterated over. Given result looks like [('MA3146', 711L, 81L), ('MA3147', 679L, 83L), ('MA3148', 668L, 86L)], a solution could be as follows.

result = [('MA3146', 711, 81), ('MA3147', 679, 83), ('MA3148', 668, 86)]
ocs, oltv = {}, {}
for pool_number, waocs, waoltv in result:
    ocs[pool_number] = int(waocs)
    oltv[pool_number] = int(waoltv)

In general, if you got a TypeError in the title (or more specifically, TypeError: tuple indices must be integers or slices, not str), see if the following captures your case.

  1. Iterate over a string and try to index a tuple. You probably never intended to iterate over a string and it should probably be a range/list etc. that returns integers.

    tpl = tuple(range(10))
    for i in '10':
        tpl[i]           # <---- TypeError: tuple indices must be integers...
    
    
    for i in range(int('10')):
        tpl[i]           # <---- OK
    
  2. Iterate over an enumerate object without unpacking. Enumerate returns a tuple of index and item pairs, which can be directly unpacked as you iterate over it.

    lst = [{'a': 1}, {'a': 2}, {'a': 3}]
    for dct in enumerate(lst):
        dct['a']                       # TypeError
    
    
    for i, dct in enumerate(lst):
        dct['a']                       # OK
    
  3. Index a namedtuple using a string. Even if namedtuple field names are defined using a string, namedtuples cannot be indexed using a string like a dict key. It can be indexed using integer indices or by field attributes.

    from collections import namedtuple
    tpl = namedtuple('Tuple', 'x, y')(x=1, y=2)
    
    tpl['a']     # <---- TypeError
    tpl[0]       # <---- OK
    tpl.x        # <---- OK
    

If you are a developer working in a Python language, for sure you may have encountered the typeerror tuple indices must be integers or slices not str.

This error can be frustrating, especially when you are not sure what it means or how to fix it.

In this article, we will explain to you the tuple indices must be integers or slices not str in more detail.

Also, provide some tips on how to resolve it.

What is a Tuple?

Before we proceed into the TypeError, it is important to know first what a tuple is.

In Python language, a tuple is an ordered collection of items. It is similar to a list, yet tuples are immutable.

That means that their contents cannot be able to change once they are created.

Why this error occur?

The tuple indices must be integers or slices not str error occurs because you are trying to access an element in a tuple using a string as the index.

Alternatively, tuples can only be accessed using integer indices or slices.

For example, let’s say you have the following tuple:

my_tuple = ('chocolate', 'strawberry', 'vanilla')
print(my_tuple['0'])

Output:

C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
Traceback (most recent call last):
File “C:UsersDellPycharmProjectspythonProjectmain.py”, line 2, in
print(my_tuple[‘0’])
TypeError: tuple indices must be integers or slices, not str

If you are trying to access the first element of the tuple using a string index.

You will get the “tuple indices must be integers or slices, not str” error message.

This is because the index ‘0’ is a string, not an integer.

Common Causes of the Error

There are multiple common causes of the error when working with tuples:

  • It is possible you are using a String Index.
  • You misspelled the Index.
  • You are trying to use a Variable as the Index.
  • It’s possible you’re trying to Modify a Tuple.

Also, read the other python error resolved:

  • Typeerror: only absolute urls are supported
  • typeerror: iteration over a 0-d array
  • Typeerror: super expression must either be null or a function

Now that you already understand some of the common causes of the error, let’s take a look at how to solve it.

Here are a few solutions to solve the error:

Solution 1: Use Integer Indices or Slices

The simple way to solve this error is to make sure that you are using integer indices or slices when accessing elements in a tuple.

For example, we will use the same example above

my_tuple = ('chocolate', 'strawberry', 'vanilla', 'butter', 'cheese')

To access an individual element of the tuple, you can use an integer below:

print(my_tuple[0])
'chocolate'

print(my_tuple[3])
'vanilla'

Let’s take an example:

my_tuple = ('chocolate', 'strawberry', 'vanilla')
print(my_tuple[0])
'chocolate'

In the first example, my_tuple[0] returns the first element of the tuple (‘chocolate’) because the index 0 is an integer.

So the output will be a chocolate:

C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
chocolate

However, to access a slice of the tuple, you can use a slice with two integer indices:

print(my_tuple[1:4])
('strawberry', 'vanilla', 'butter')

In the second example, my_tuple[1:4] returns a slice of the tuple that includes elements with indices 1, 2, and 3 (‘strawberry’, ‘vanilla’, ‘butter’, respectively).

Let’s take a look another example:

my_tuple = ('chocolate', 'strawberry', 'vanilla', 'butter', 'cheese')
print(my_tuple[1:4])
('strawberry', 'vanilla', 'butter')

Output:

C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
(‘strawberry’, ‘vanilla’, ‘butter’)

Through using integer indices or slices, you can prevent the “TypeError: tuple indices must be integers or slices, not str” error.

Solution 3: Check Your Spelling

If you are getting the error due to a misspelled index.

Remember always that you need to double-check your spelling to make sure that you are using the correct index.

Solution 4: Convert Variables to Integers

When you are trying to use a variable as the index, make sure that you convert it to an integer first.

For example:

We assume you have a tuple of numbers:

my_tuple = (10, 20, 30, 40, 50)

And you have a variable that consists a string that defines an integer:

my_index = '2'

Example: the output will be an error

my_tuple = (10, 20, 30, 40, 50)
my_index = '2'
print(my_tuple[my_index])

Output:

C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
Traceback (most recent call last):
File “C:UsersDellPycharmProjectspythonProjectmain.py”, line 3, in
print(my_tuple[my_index])
TypeError: tuple indices must be integers or slices, not str

If you are trying to use the my_index variable as an index directly, you will get a “TypeError tuple indices must be integers or slices, not str” error:

To solve this error, you can convert the my_index variable to an integer using the int() function:

For the correct example:

my_tuple = (10, 20, 30, 40, 50)
my_index = '3'
print(my_tuple[int(my_index)])

Output:

C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
40

In this example, int(my_index) returns the integer value 3.

Which is used as the index to access the third element of the my_tuple tuple (40).

By converting the string variable to an integer before using it as an index, you can prevent the error.

Solution 3: Use Lists Instead of Tuples

If you need to change the contents of a collection, you can use a list instead of a tuple.

Lists are similar to tuples, yet they are mutable, it means that you can change their contents.

Suppose you have a tuple of numbers:

my_tuple = (10, 20, 30, 40, 50)
my_tuple[1] = 25

And you want to change one of the elements of the tuple (e.g., change the second element from 20 to 25). Tuples are immutable, so you cannot modify their elements directly.

If you try to do so, you will get a “TypeError: ‘tuple’ object does not support item assignment” error:

C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
Traceback (most recent call last):
File “C:UsersDellPycharmProjectspythonProjectmain.py”, line 2, in
my_tuple[1] = 25
TypeError: ‘tuple’ object does not support item assignment

To solve this error, you can use a list instead of a tuple.

Lists are mutable, so you can change their elements directly.

Here’s how you can create a list from the tuple:

my_list[1] = 25

And if you want to convert the list back to a tuple, you can use the tuple() function:

my_new_tuple = tuple(my_list)

Now my_new_tuple is a tuple with the changed element:

print(my_new_tuple)
(10, 25, 30, 40, 50)

Let’s take a complete example below;

my_tuple = (10, 20, 30, 40, 50)
my_list[1] = 25
my_new_tuple = tuple(my_list)
print(my_new_tuple)
(10, 25, 30, 40, 50)

Output:

C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
(10, 25, 30, 40, 50)

By using a list instead of a tuple, you can change its elements directly and you can prevent the error.

FAQs

Can I use a string index to access elements in a tuple?

No, you cannot use a string index to access elements in a tuple. Tuples can only be accessed using integer indices or slices.

Can I modify the contents of a tuple?

No, tuples are immutable, which means that their contents cannot be changed once they are created.

What is the difference between a list and a tuple?

Lists and tuples are both collections of items in Python. The main difference between them is that lists are mutable, while tuples are immutable.

Conclusion

The “tuple indices must be integers or slices, not str” can be confusing.

Yet it is usually easy to solve once you know the cause of the error.

In most cases, it is caused by using a string index instead of an integer index or slice.

By using the solutions provided in this article, you should be able to solve the error quickly and easily.

async def chekc_balance(self, user):
        async with self.pool.acquire() as conn:
            async with conn.cursor() as cur:
                result = await cur.execute("SELECT * FROM profile WHERE uid=%s", user.id)
                row = await cur.fetchall()
                if result == 1:
                    await cur.execute("UPDATE profile SET balance=balance WHERE uid=%s", user.id)
                    return row['balance']

@command(name="кошелёк")
    async def prov(self, ctx):
        user = await self.bot.get_user(ctx.from_id)
        balance = await basa.register.main.chekc_balance(user)
        return await ctx.send(f"В кошельке: {balance}n"
                              f"На карточке:n")

Ошибка:

raise CommandInvokeError(exc) from exc vk_botting.exceptions.
CommandInvokeError: 
Command raised an exception: 
TypeError: tuple indices must be integers or slices, not str

Как исправить ошибку?

Last updated on 
Sep 29, 2020

Have you tried to iterate over a DataFrame in Pandas, but got a TypeError: tuple indices must be integers or slices, not str ? If so, we’ll see what is the cause of the error and how to solve it.

1: Create simple DataFrame

To begin lets create simple DataFrame:

df = pd.DataFrame({'num_legs': [4, 2, 0], 'num_wings': [0, 2, 0]},
                  index=['dog', 'hawk', 'fish'])

data:

num_legs num_wings
dog 4 0
hawk 2 2
fish 0 0

2: TypeError: tuple indices must be integers or slices, not str

If we like to iterate row by row and access the row data then we can use method: pandas.DataFrame.iterrows. A common problem for programmers is to not read docs(including me sometimes :) ) and go with solution like:

for row in df.iterrows():
    print(row['num_wings'])

but this leads to the error which is the topic of the article:

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

3: Solution for TypeError: tuple indices must be integers or slices, not str

Reading the docs of pandas.DataFrame.iterrows we can find that:

Iterate over DataFrame rows as (index, Series) pairs.

which means that usage above is not correct. The correct code and the solution for TypeError: tuple indices is:

for index, row in df.iterrows():

full code:

for index, row in df.iterrows():
    print(row['num_wings'])

now the result is:

0
2
0

4: Analyse similar errors like: TypeError: tuple indices must be integers or slices, not str

I’ve recommend to you to look at the error more carefully and find the problematic line:

TypeError                                 Traceback (most recent call last)
<ipython-input-18-4ab72df7c78e> in <module>
      1 for row in df.iterrows():
----> 2     print(row['num_wings'])

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

then start removing or simplifying the line like:

print(row['num_wings']) -> print(row)

and check what happens. Another way is by debugging and using evaluate expression. You can find more advanced techniques for debugging here: PyCharm — Breakpoints, Favorites, TODOs simple examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import random
import sys
 
WIDTH = 8
HEIGHT = 8
 
def drawBoard(board):
    print(' 12345678')
    print(' +--------+')
    for y in range(HEIGHT):
        print('%s|' % (y+1), end='')
        for x in range(WIDTH):
            print(board[x][y], end='')
        print('%s|' % (y+1))
    print(' +--------+')
    print(' 12345678')
 
def getNewBoard():
    board = []
    for i in range(WIDTH):
        board.append([' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '])
    return board
 
def isValidMove(board, tile, xstart, ystart):
    if board[xstart][ystart] != ' ' or not isOnBoard(xstart, ystart):
        return False
 
    if tile == 'X':
        otherTile = 'O'
    else:
        otherTile = 'X'
 
    tilesToFlip = []
    for xdirection, ydirection in [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]:
        x, y = xstart, ystart
        x += xdirection #Первый шаг в направлении х
        y += ydirection #Первый шаг в направлении у
        while isOnBoard(x, y) and board[x][y] == otherTile:
            x += xdirection
            y += ydirection
            if isOnBoard(x, y) and board[x][y] == tile:
                while True:
                    x -= xdirection
                    y -= ydirection
                    if x == xstart and y == ystart:
                        break
                    tilesToFlip.append([x, y])
 
    if len(tilesToFlip) == 0:
        return False
    return tilesToFlip
 
def isOnBoard(x, y):
    return x >= 0 and x <= WIDTH - 1 and y >= 0 and y <= HEIGHT - 1
 
def getBoardWithValidMoves(board, tile):
    boardCopy = getBoardCopy(board)
 
    for x, y in getValidMoves(boardCopy, tile):
        boardCopy[x][y] = '.'
    return boardCopy
 
def getValidMoves(board, tile):
    validMoves = []
    for x in range(WIDTH):
        for y in range(HEIGHT):
            if isValidMove(board, tile, x, y) != False:
                validMoves.append([x, y])
    return validMoves
 
def getScoreOfBoard(board):
    xscore = 0
    oscore = 0
    for x in range(WIDTH):
        for y in range(HEIGHT):
            if board[x][y] == 'X':
                xscore += 1
            if board[x][y] == 'O':
                oscore += 1
    return ('X ' + str(xscore), 'O ' + str(oscore))
 
def enterPlayerTile():
    tile = ''
    while not (tile == 'X' or tile == 'O'):
        print('Вы играете за Х или О???')
        tile = input().upper()
 
    if tile == 'X':
        return ['X', 'O']
    else:
        return ['O', 'X']
 
def whoGoesFirst():
    if random.randint(0, 1) == 0:
        return 'Компьютер'
    else:
        return 'Человек'
 
def makeMove(board, tile, xstart, ystart):
    tilesToFlip = isValidMove(board, tile, xstart, ystart)
 
    if tilesToFlip == False:
        return False
 
    board[xstart][ystart] = tile
    for x, y in tilesToFlip:
        board[x][y] = tile
    return True
 
def getBoardCopy(board):
    boardCopy = getNewBoard()
 
    for x in range(WIDTH):
        for y in range(HEIGHT):
            boardCopy[x][y] = board[x][y]
 
    return boardCopy
 
def isOnCorner(x, y):
    return (x == 0 or x == WIDTH - 1) and (y == 0 or y == HEIGHT - 1)
 
def getPlayerMove(board, playerTile):
    DIGITS1TO8 = '1 2 3 4 5 6 7 8'.split()
    while True:
        print('Укажите ход, текст "Выход" для завершения игры или "Подсказка" для вывода подсказки')
        move = input().lower()
        if move == 'Выход' or move == 'Подсказка':
            return move
 
        if len(move) == 2 and move[0] in DIGITS1TO8 and move[1] in DIGITS1TO8:
            x = int(move[0]) - 1
            y = int(move[1]) - 1
            if isValidMove(board, playerTile, x, y) == False:
                continue
            else:
                break
        else:
            print('Это недопустимый ход. Введите номер столбца (1-8) и номер ряда (1-8)')
            print('К примеру, 81 перемещает в верхний правый угол')
 
    return [x, y]
 
def getComputerMove(board, computerTile):
    possibleMoves = getValidMoves(board, computerTile)
    random.shuffle(possibleMoves)
 
    for x, y in possibleMoves:
        if isOnCorner(x, y):
            return [x, y]
 
    bestScore = -1
    for x, y in possibleMoves:
        boardCopy = getBoardCopy(board)
        makeMove(boardCopy, computerTile, x, y)
        score = getScoreOfBoard(boardCopy)[computerTile]
        if score > bestScore:
            bestMove = [x, y]
            bestScore = score
    return bestMove
 
def printScore(board, playerTile, computerTile):
    scores = getScoreOfBoard(board)
    print('Ваш счет: %s. Счет компьютера: %s.' % str((scores[playerTile, scores[computerTile]])))
 
def playGame(playerTile, computerTile):
    showHints = False
    turn = whoGoesFirst()
    print(turn + ' ходит первым')
 
    board = getNewBoard()
    board[3][3] = 'X'
    board[3][4] = 'O'
    board[4][3] = 'O'
    board[4][4] = 'X'
 
    while True:
        playerValidMoves = getValidMoves(board, playerTile)
        computerValidMoves = getValidMoves(board, computerTile)
 
        if playerValidMoves == [] and computerValidMoves == []:
            return board
        elif turn == 'Человек':
            if playerValidMoves != []:
                if showHints:
                    validMovesBoard = getBoardWithValidMoves(board, playerTile)
                    drawBoard(validMovesBoard)
                else:
                    drawBoard(board)
                printScore(board, playerTile, computerTile)
                move = getPlayerMove(board, playerTile)
                if move == 'Выход' or 'выход':
                    print('Благодарим за игру!')
                    sys.exit()
                elif move == 'Подсказка' or 'подсказка':
                    showHints = not showHints
                    continue
                else:
                    makeMove(board, playerTile, move[0], move[1])
            turn = 'Компьютер'
 
        elif turn == 'Компьютер':
            if computerValidMoves != []:
                drawBoard(board)
                printScore(board, playerTile, computerTile)
 
                input('Нажмите ENTER для просмотра хода компьютера')
                move = getComputerMove(board, computerTile)
                makeMove(board, computerTile, move[0], move[1])
            turn = 'Человек'
 
playerTile, computerTile = enterPlayerTile()
 
while True:
    finalBoard = playGame(playerTile, computerTile)
 
    drawBoard(finalBoard)
    scores = getScoreOfBoard(finalBoard)
    print('X набрал %s очков. О набрал %s очков.' % str((scores['X'], scores['O'])))
    if scores[playerTile] > scores[computerTile]:
        print("Вы победили компьютер, обогнав его на %s очка(ов)!" % str((scores[playerTile] - scores[computerTile])))
    elif scores[playerTile] < scores[computerTile]:
        print('Вы проиграли. Компьютер обогнал вас на %s очка(ов)' % str((scores[computerTile] - scores[playerTile])))
    else:
        print("Ничья")
input()

Возможно, вам также будет интересно:

  • Tumblr ошибка при загрузке форм
  • Ts4 exe ошибка приложения симс 4 что делать
  • Ts3w exe ошибка приложения как исправить sims 3
  • Ts3client win64 exe системная ошибка
  • Ts3100 series коды ошибок

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии