2

I need to keep catching an exception while indexing a list throws a IndexError exception, for example:

l = []
while((l[3]) throws IndexError):
    //Add more data to the list
    l += [3]

How can I keep checking to see if the method call has thrown an exception without having nested a nested try/catch block?

4
  • Why would you not want to use a try:... except: block? It's Pythonic. Commented Mar 17, 2014 at 10:18
  • 1
    You might find my answer to this question useful. Commented Mar 17, 2014 at 10:19
  • @BurhanKhalid The number being indexed changes each run, this is dependant because it is reading in data from the USB port. Commented Mar 17, 2014 at 10:30
  • 1
    Doing this with an exception or any sort of "until we have enough" loop seems silly. Why not just compare the length you need to the length you have and add the amount of data you need? if len(l) < needed: l += [3] * (needed - len(l)) Commented Mar 17, 2014 at 10:38

1 Answer 1

4

It depends what you would like to extend your list with. Assuming 'None' you could do it like this:

l = []
while True:
  try:
    l[3] = 'item'
    break
  except IndexError:
    l.extend([None])

print l # [None, None, None, 'item']
Sign up to request clarification or add additional context in comments.

2 Comments

I hadn't thought of wrapping this in a infinite loop, partly because in my application its already wrapped in an infinite loop and don't want it to become uncontrollable.
You could do: while len(l) <= 4: (4 not 3 because indexing starts with 0) or even wrap this into a function and have the index as argument

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.