How to insert into python nested list

前端 未结 2 578
太阳男子
太阳男子 2020-12-11 21:50

I want to insert an item into a list inside a list. I\'m wondering if someone can show me.

list5 = [[], [(1,2,3,4), 2, 5]]
print(\"1. list5\", list5)
list5.i         


        
2条回答
  •  难免孤独
    2020-12-11 22:22

    The issue here is that insert creates a new item in the list that it is applied to. So

    >>> list5 = [[], [(1,2,3,4), 2, 5]]
    

    creates a list with two elements, the first of which happens to be a list with zero elements:

    >>> list5[0]
    ## []
    

    If you then call list5.insert(0, foo), what will happen is that foo gets pushed into the list at position 0, and everything else gets shoved along (i.e. the elements of the list which had an index of 0 or greater each get their index increased by 1).

    What you actually want to do is to insert an element into the empty list at position 0 of list5. So you need to access that list, and then call a method that adds your element. Either

    >>> list5[0].append( (2,5,6,8) )
    

    or

    >>> list5[0].insert(0, (2,5,6,8) )
    

    will do the trick.

提交回复
热议问题