Where goes wrong in this list manipulation?

前端 未结 2 1707
感情败类
感情败类 2021-01-20 15:52

I am manipulating with the lists in Python.

In [52]: myList = [1,2,3,4,5]
In [54]: c=[[]]*10

In [55]: for i, elem1 in enumerate(myList):
   ....:     b = [e         


        
相关标签:
2条回答
  • 2021-01-20 16:13

    The source of your confusion is on this line

    c=[[]]*10
    

    Here you are creating a list of ten references to the same (initially empty) list. Thus as you append to the list in c[0] later on, you are also appending to every other list in c. Try

    c = [ [] for _ in range(10) ]
    

    This will create a new list 10 ten times, so you won't have the same referencing problem.

    0 讨论(0)
  • 2021-01-20 16:27

    Lists in c are all the same object. You need to do at least:

    c = [[] for i in xrange(10)]
    
    0 讨论(0)
提交回复
热议问题