Python 限制列表的长度

Python 限制列表的长度,python,Python,我不知道是否有人问过这个问题,但我没有找到 我正在将元素添加到列表中 thr_core0 +=[fpid[thread]] 这是周期性的。。 在时间0: thr_core0[98869890] 在时间1: thr_core0[9886989098869890] 是否可以将列表的长度限制为2 我知道可以使用deque。但是也可以使用列表 使用deque,我们可以这样做: thr_core0 += [deque([0]*2,maxlen=2)] 以下是我在谷歌上搜索到的关键词:limitlist

我不知道是否有人问过这个问题,但我没有找到

我正在将元素添加到列表中

thr_core0 +=[fpid[thread]]
这是周期性的。。 在时间0:

thr_core0[98869890]

在时间1:

thr_core0[9886989098869890]

是否可以将列表的长度限制为2

我知道可以使用
deque
。但是也可以使用
列表

使用
deque
,我们可以这样做:

thr_core0 += [deque([0]*2,maxlen=2)]

以下是我在谷歌上搜索到的关键词:
limit
list
length
python
它不漂亮,但你可以将其切分:

thr_core0 = (thr_core0 + [fpid[thread]])[:2]

这将始终确保
core0
最多有两个元素。

技术上是的-但您不想-这就是
deque
的用途…您对
deque
的使用似乎不正确。您可能需要:
thr\u core0=deque([0]*2,maxlen=2);附加(9886)好的。在这种情况下,我将使用deque。但是,这个答案必须打勾。@rnish:要保留最后两个值而不是前两个值:
L=L[-2:]