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
elif index < list_length:
# add element at the given index
# index is out of bound ~ what will happen when an element will be added at this index?
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
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