Python列表布尔索引访问元素:为何布尔值可用于列表索引?
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, thebooltype is a subclass ofint. That meansFalseis essentially the integer0, andTrueis the integer1. You can test this yourself with quick checks:print(int(False)) # Output: 0 print(int(True)) # Output: 1 print(isinstance(False, int)) # Output: TrueLists 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: MarkBecause
True + Trueequals2, 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

