double square brackets side by side in python

前端 未结 2 1495
-上瘾入骨i
-上瘾入骨i 2021-01-02 01:52

I\'m completely new at Python and have an assignment coming up. The professor has asked that we look at examples of users coding Pascal\'s Triangle in Python for something t

相关标签:
2条回答
  • 2021-01-02 02:26

    Square brackets are used to define lists, but also to get things from lists.

    When you have a list of lists and want something from an inner list, you need to get that inner list (using brackets) and then get the desired thing inside (using brackets again).

    lol = [[1, 2, 3], [4, 5, 6]]
    lol[1]
    # [4, 5, 6]
    lol[1][0]
    # 4
    
    0 讨论(0)
  • 2021-01-02 02:37

    If you have a list

    l = ["foo", "bar", "buz"]
    

    Then l[0] is "foo", l[1] is "bar", l[2] is buz.

    Similarly you could have a list in it instead of strings.

    l = [ [1,2,3], "bar", "buz"]
    

    Now l[0] is [1,2,3].

    What if you want to access the second item in that list of numbers? You could say:

    l[0][1]
    

    l[0] first gets you the list, then [1] picks out the second number in it. That's why you have "square bracket next to square bracket".

    0 讨论(0)
提交回复
热议问题