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

Python列表布尔索引访问元素:为何布尔值可用于列表索引?

Why does boolean indexing work on Python lists?

Great question! This behavior might seem weird at first, but it all clicks once you understand how Python treats boolean values behind the scenes. Let’s break it down simply:

  • Booleans are just special integers
    In Python, the bool type is a subclass of int. That means False is essentially the integer 0, and True is the integer 1. You can test this yourself with quick checks:

    print(int(False))  # Output: 0
    print(int(True))   # Output: 1
    print(isinstance(False, int))  # Output: True
    
  • Lists use integer-based indexing
    When you access a list element with [index], Python expects an integer (or a slice, but that’s a separate topic). If you pass a boolean instead, Python automatically converts it to its integer equivalent.

    Applying this to your example:

    • ["Peter", "James", "Mark"][False] gets converted to ["Peter", "James", "Mark"][0], which pulls the first element ("Peter").
    • ["Peter", "James", "Mark"][True] gets converted to ["Peter", "James", "Mark"][1], which pulls the second element ("James").
  • A fun extra test
    If you wanted to grab the third element ("Mark") using booleans, you could even do this:

    print(["Peter", "James", "Mark"][True + True])  # Output: Mark
    

    Because True + True equals 2, the index of the third element.

Quick best practice note

While this works, it’s not a good idea to use in real code. Boolean indexes are confusing to other developers (and future you!)—it’s way clearer to just use explicit integer indexes like 0, 1, or 2 instead.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:16:38