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

Python中如何获取列表的第一个元素

Python获取列表第一个元素的实现方案

现有代码场景

obj = ['Execute', 'execute', 'VERB']

if obj is not None:
    for token in obj :
        ....???

需求为获取上述obj列表的第一个元素。

具体实现方式

  • 直接索引取值(推荐,无需循环)
    Python列表属于有序序列,索引从0开始计数,直接通过列表名[0]即可获取第一个元素,是最简单高效的写法。
    注意现有代码只判断了obj不是None,为了避免空列表触发索引越界错误,建议补充列表非空判断,示例代码如下:
    obj = ['Execute', 'execute', 'VERB']
    
    if obj is not None and len(obj) > 0:
        first_item = obj[0]
        print(first_item)  # 运行输出:Execute
    
  • 若需要在现有for循环逻辑中拿到第一个元素,可以借助enumerate()遍历索引,判断索引为0时的元素即可:
    obj = ['Execute', 'execute', 'VERB']
    
    if obj is not None:
        for index, token in enumerate(obj):
            if index == 0:
                first_item = token
                # 这里写你需要对第一个元素执行的处理逻辑
            # 其余原有循环逻辑
    

提示:如果没有必须遍历全量列表的需求,优先用直接索引的写法,代码更简洁,执行效率也更高。

内容的提问来源于stack exchange,提问作者Sathish Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 17:18:05