How to add element in Python to the end of list using list.insert?

前端 未结 2 1252
北荒
北荒 2020-12-14 13:53

There is a list, for example,

a=[1,2,3,4]

I can use

a.append(some_value)

to add element at the end of l

相关标签:
2条回答
  • 2020-12-14 14:52

    You'll have to pass the new ordinal position to insert using len in this case:

    In [62]:
    
    a=[1,2,3,4]
    a.insert(len(a),5)
    a
    Out[62]:
    [1, 2, 3, 4, 5]
    
    0 讨论(0)
  • 2020-12-14 14:55

    list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append

    Python 3.7.4
    >>>lst=[10,20,30]
    >>>lst.insert(len(lst), 101)
    >>>lst
    [10, 20, 30, 101]
    >>>lst.insert(len(lst)+50, 202)
    >>>lst
    [10, 20, 30, 101, 202]
    

    Time complexity, append O(1), insert O(n)

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