Entry
How can I insert a node in a list?
Mar 28th, 2002 08:14
Michael Chermside,
The insert() method will allow one node to be inserted, or assigning to
a slice provides an easy way to insert multiple values. Here's how it works:
>>> alist = [1, 2, 3, 4, 5, 6, 7]
>>> alist.insert(3, 'abc')
>>> alist
[1, 2, 3, 'abc', 4, 5, 6, 7]
>>> alist[6:6] = ['x', 'y', 'z']
>>> alist
[1, 2, 3, 'abc', 4, 5, 'x', 'y', 'z', 6, 7]
It is worth noting that both of these operations take O(N) time, where N
is the number of items after the insertion. Python lists are optimized
to perform well under repeated additions to the end of the list, but
insertions aren't quite as well optimized.