Home > database >  Unexpected type error raised with list in PyCharm
Unexpected type error raised with list in PyCharm

Time:11-09

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(0)]
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. I wonder why PyCharm would give this error and how can I solve this with cleanest code. Thanks.

CodePudding user response:

this is just a warning from the code inspection tool.

It is basically saying that you created a list of integers (containing five items equal to 0), and then you are replacing one integer with a string.

This does not generate errors in python, as it is extremely flexible with the data types, and you can generate list with different data types if you want.

It is just warning you that something might go wrong if you use that list later in some code that expects only integers and finds instead an item that is a string.

You can solve this by disabling the inspection, or by creating directly a list of strings.

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

or also

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

Or you can just ignore the warning, provided that you keep in mind that the list might contain different data types.

CodePudding user response:

You can't assign to a list like list2 unless you've already initialized the list with n 1 elements.

list2 = [0 for n in range(0)] is the same as list2 = []. Try using append to add elements to the end of the list

>>> list2.append('')
>>> list2[0]
''
  • Related