Search code examples
pythonpython-3.xpycharm

Unexpected type warning raised with list in PyCharm


Right to the point, here below is the sample code which will raise error in PyCharm:

list1 = [0] * 5
list1[0] = ''
list2 = [0 for n in range(5)]
list2[0] = ''

PyCharm then return an error on both line 2 and line 4 as below:

Unexpected type(s):(int, str)Possible type(s):(SupportsIndex, int)(slice, Iterable[int])

Running the code would not cause any error, but PyCharm keep raising the above message when I am coding.

Why PyCharm would give this error and how can I solve this with cleanest code?


Solution

  • In your case PyCharm sees you first line and thinks that the type of list is List[int]. I mean it is a list of integers.

    You may tell that you list is not int-typed and can accept any value this way:

    from typing import Any, List
    
    list1: List[Any] = [0] * 5
    list1[0] = ''
    

    I used typing module just to explain the idea. Here is a simple way to announce that list1 is just a list of anything:

    list1: list = [0] * 5
    list1[0] = ''
    

    Also consider to use as strict typing as possible. It may help you to prevent bugs.

    If you need both strings and ints then use this:

    from typing import List, Union
    
    list1: List[Union[int, str]] = [0] * 5
    # Starting from Python 3.10 you may use List[int|str] instead 
    

    Docs here: https://docs.python.org/3/library/typing.html