How to grow a list so that it matches the given capacity in Python

I am new to Python. I have a number of objects that need to be inserted at certain indexes on the list, but they fail, so I can’t just add them. How can I grow a list when necessary to avoid IndexErrors?

def set(index, item):
    if len(nodes) <= index:
        # Grow list to index+1
    nodes[index] = item

I know that you can create a list with an initial throughput through nodes = (index+1) * [None], but what is the usual way to grow it? The following functions do not seem to be effective:

for _ in xrange(len(nodes), index+1):
    nodes.append(None)

Also, I suppose there is a class in the standard library that I should use instead of inline lists?

+3
source share
3 answers

This is the best way to do this.

>>> lst.extend([None]*additional_size)
+7
source

Maybe something like:

lst += [None] * additional_size

( , ).

+1

oops , . , , - , , , lst.extend([None]*(new_size - len(lst)), , , . , , , None s.


: - , - , . insert , . set

lst.insert(item, index)

lst[index:index] = item

which does the same thing. Python will take care of resizing the list for you.

It is not necessary to use a class in the standard library that you should use instead list, especially if you need such a random access feature. However, there are several classes in the module collectionsthat you should be aware of, since they can be useful for other situations (for example, if you're always added to one end of the list, and you don't know in advance how many elements you need, dequeit would be appropriate).

+1
source

All Articles