Reference an Element in a List of Tuples

后端 未结 7 416
无人共我
无人共我 2020-12-08 10:37

Sorry in advance, but I\'m new to Python. I have a list of tuples, and I was wondering how I can reference, say, the first element of each tuple w

7条回答
  •  轮回少年
    2020-12-08 11:16

    The code

    my_list = [(1, 2), (3, 4), (5, 6)]
    for t in my_list:
        print t
    

    prints

    (1, 2)
    (3, 4)
    (5, 6)
    

    The loop iterates over my_list, and assigns the elements of my_list to t one after the other. The elements of my_list happen to be tuples, so t will always be a tuple. To access the first element of the tuple t, use t[0]:

    for t in my_list:
        print t[0]
    

    To access the first element of the tuple at the given index i in the list, you can use

    print my_list[i][0]
    

提交回复
热议问题