Alisan26
Alisan26

Reputation: 323

TypeError: 'int' object has no attribute '__getitem__' in Python enumerate

Hi I have code like below

my tupleList is =[(0, '1.example'), (1, '2.example'), (2, '3. example'), (3, '4. example'), 0]

Index = [x for x, y in enumerate(tupleList[0]) if y[0] == control]
self.list["list_key"].append(tupleList[0][Index[0]][1])

and my control variable is 1 and type int, I trying reach to '2.example' in tuple,

getting error

TypeError: 'int' object has no attribute '__getitem__' in Python

changing my tuple is = [('E', '1 examp'), ('H', '2 examp'), 'E']

like this and my control variable is 'E' is wont problem, code is working but I changing tupleList = [(0, '1.example'), (1, '2.example'), (2, '3. example'), (3, '4. example'), 0] and control variable to 1, I getting error

How can I procces this tupleList

Upvotes: 0

Views: 250

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599946

This is because strings are iterable, but ints aren't.

You could explicitly check for an integer:

[x for x, y in enumerate(tupleList[0]) if not isinstance(y, int) and y[0] == control]

or perhaps more generically:

from typing import Iterable
[x for x, y in enumerate(tupleList[0]) if isinstance(y, Iterable) and y[0] == control]

Upvotes: 1

Related Questions