Search code examples
pythonpython-3.xlistlist-comprehension

Understanding multiplication syntax with Lists


I understand the below list concatenation:

r = [1, 2] + [False]
# Output: r = [1, 2, False]

However, I am not able to understand the below syntax:

r = [1, 2][False]
# Output: 1

Solution

  • You're defining an unnamed list, then indexing it with False. Because False has a numeric value of zero (bool is actually a subclass of int, where False has a value 0, and True has a value 1), that's equivalent to indexing it as index 0, so it's like you wrote:

    __unnamed = [1, 2]
    r = __unnamed[0]