2

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.

1
  • 1
    append accepts 1 argument and adds it at the end. Maybe you want ìnsert. Commented Feb 28, 2013 at 14:14

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Under what conditions will insert raise IndexError? I'm playing around with python 3.3 and large negative indexes add to the beginning of the list. Large positive indexes add to the end. Indexes in range(1, len(list)-1) add to the middle. I can't get an IndexError with insert.
@EricRoper: Ah, of course, you are right. It will never raise. And the funny thing is that I knew that... Corrected.
3

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.

Comments

0

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

4 Comments

a[index] = value replaces the value at that index. It is not the equivalent of an insert.
I've added a note about that
But the function name is add_release(), so why overwrite existing values?
I do not want to overwrite. But I think he just wants to add another "related" operation, and that is good for learning! But 1 up for the smart catch with the method name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.