You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyCharm中列表赋值触发Unexpected type警告的原因及简洁解决方法

Why PyCharm Throws That Type Warning (And How to Fix It)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 00:47:30