A
A
Andrey Godunko2021-12-12 10:45:27
Python
Andrey Godunko, 2021-12-12 10:45:27

How to fix TypeError: 'type' object is not subscriptable?

with open('input.txt', 'r') as f:
    num = list(map(int, f.read().split()))

Here is my code. And it turns out that the data is written to a tuple, and I need to edit the list. But if I do this, num = list(map[int, f.read().split()]) that is, I rewrite it in a regular list, then it writes an error . I couldn't find an answer on the internet that worked for me.... TypeError: 'type' object is not subscriptable

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-12-12
@Noy-name-boy

Ufff. Here we are talking about the basics of Python syntax.
Your first code does the following.

num = list( #построить список из последовательности
    map( #вызываем функцию map()
        int, #первый параметр
        f.read().split() #второй параметр
    )
)

And the second code does (or rather tries) this:
num = list( #построить список из последовательности
    map[ #обращаемся к объекту map и пытаемся получить значение по ключу
        int, #первый элемент кортежа-ключа
        f.read().split() #второй элемент кортежа-ключа
    ]
)

Since map is not a dictionary or similar collection, this of course doesn't work, and generates exactly the error you specified.
I don’t understand where the idea came from that you can simply replace parentheses with square brackets in a function call if they have completely different semantics.
Well, yes, there can be nothing but a list in the output, since the result of the map () operation (and this will be a generator object) is explicitly converted into a list.
In general, the above was correctly advised - read the textbook, the same Mark Lutz, "Learning Python", at least the 4th edition. At least such errors will disappear.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question