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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With