问题描述:

I would like to know if there is a more pythonic way to add an element to a list, depending on an (default) index. And what happens if the index is out of bounds. (I'm coming from Java)

self.releases = []

def add_release(self, release, index=-1):

list_length = len(self.releases)

if index < 0:

# add element at the end of the list

self.releases.append(release)

elif index < list_length:

# add element at the given index

self.releases.insert(index, release)

else:

# index is out of bound ~ what will happen when an element will be added at this index?

pass

Thanks in advance.

网友答案:

Leave the index at -1, and catch exceptions instead:

def add_release(self, release, index=-1):
    self.releases.insert(index, release)

When you use .insert() with a negative index, the item is inserted relative to the length of the list. Out-of-bounds indices are brought back to bounds; inserting beyond the length is the same as appending, insertion before the 0 index inserts at 0 instead.

网友答案:

List.append() only ever takes one argument - a value to append to the list. If you want to insert in an arbitrary location, you need the List.insert(), which treats out-of-range position arguments as a call to append.

网友答案:

Try to have a look at the insert method

a=[]
a.insert(index, value)

If you are sure that you are not out of bounds, you can also

a[index] = value

note that it will overwrite the value at the given index if there is any

相关阅读:
Top