Search code examples
pythonlistgetlinelinecache

TypeError while working with a Python list


In the following code fragment:

def func_5_2(datei, num):
    import linecache
    i = 0
    number = num + 1
    l = []
    while True:
        l[i] = linecache.getline(datei, number)
        if (l[i] == ''):
            break

Is it possible to fix the problem I get on this line?

list[i] = linecache.getline(datei, number)

Here's the error I get:

File "/home/user/gosection.py", line 27, in func_5_2
  list[i] = linecache.getline(datei, number)
TypeError: 'type' object does not support item assignment

Thanks for your help!


Solution

  • You get this exception because the object list is never defined. Initialize list before using it.

    For example like this:

    list = []
    

    Your code is trying to assign an item to the builtin sequence type list.

    It is not a good practice to name variables like existing types... Give the variable another name like lines:

    >>> lines = []
    >>> type(lines)
    <class 'list'>