Python: list of lists

前端 未结 7 1145
夕颜
夕颜 2020-11-27 04:38

Running the code

listoflists = []
list = []
for i in range(0,10):
    list.append(i)
    if len(list)>3:
        list.remove(list[0])
        listoflists.         


        
7条回答
  •  误落风尘
    2020-11-27 05:12

    First, I strongly recommend that you rename your variable list to something else. list is the name of the built-in list constructor, and you're hiding its normal function. I will rename list to a in the following.

    Python names are references that are bound to objects. That means that unless you create more than one list, whenever you use a it's referring to the same actual list object as last time. So when you call

    listoflists.append((a, a[0]))
    

    you can later change a and it changes what the first element of that tuple points to. This does not happen with a[0] because the object (which is an integer) pointed to by a[0] doesn't change (although a[0] points to different objects over the run of your code).

    You can create a copy of the whole list a using the list constructor:

    listoflists.append((list(a), a[0]))
    

    Or, you can use the slice notation to make a copy:

    listoflists.append((a[:], a[0]))
    

提交回复
热议问题