Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding item to a list in a Pythonic way

Tags:

python

list

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.

like image 526
user937284 Avatar asked Nov 29 '25 16:11

user937284


2 Answers

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.

like image 199
Martijn Pieters Avatar answered Dec 02 '25 07:12

Martijn Pieters


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.

like image 44
RoadieRich Avatar answered Dec 02 '25 06:12

RoadieRich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!