PyCharm中列表赋值触发Unexpected type警告的原因及简洁解决方法
First off, that Unexpected type(s):(int, str) warning isn’t an error—it’s PyCharm’s static type checker doing its job. Here’s why it pops up:
When you create list1 = [0] * 5 or list2 = [0 for n in range(5)], PyCharm looks at the initial elements (all integers) and infers that the list should only hold integers (type list[int]). When you later assign a string to an index in that list, it sees a mismatch between the expected type (int) and the one you’re putting in (str), hence the warning:
Unexpected type(s):(int, str)
Possible type(s):(SupportsIndex, int)(slice, Iterable[int])
Even though Python is dynamically typed (so the code runs without issues), PyCharm is flagging this as a potential accidental mistake—like if you meant to assign an integer but slipped up and used a string.
Now, for the simplest fixes:
1. Modern Python (3.9+): Use Union Types Directly
This is the cleanest and most concise solution, no imports needed:
list1: list[int | str] = [0] * 5 list1[0] = '' # No warning anymore! list2: list[int | str] = [0 for n in range(5)] list2[0] = '' # Same here
By annotating the list as list[int | str], you’re telling PyCharm explicitly that this list can hold both integers and strings.
2. Older Python Versions (Pre-3.9): Import from typing
If you’re stuck on Python 3.8 or earlier, you’ll need to use the Union type from the typing module:
from typing import List, Union list1: List[Union[int, str]] = [0] * 5 list1[0] = '' list2: List[Union[int, str]] = [0 for n in range(5)] list2[0] = ''
3. Quick Fix Without Annotations: Type Comments
If you don’t want to use formal type annotations, a type comment works too:
list1 = [0] * 5 # type: list[int | str] list1[0] = ''
All these methods will silence the warning while keeping your code valid and running as expected.
Content of the question comes from Stack Exchange, asked by Gordon Hui

