tags:

views:

72

answers:

2

Hello

I am looking for a list functionnality in Python.

I am doing this :

abcd = [1, 2, 3, 4]
try:
    item = list[5]
except:
    item = 0

How can I make it looks like :

item = abcd.get(5, 0)

Thanks for your help

+3  A: 

You cannot add a get method to the list class, but you can use either a function:

def get(alist, index, default):
  try: return alist[index]
  except IndexError: return default

which gives you the usage example:

abcd = [1, 2, 3, 4]
item = get(abcd, 5, 0)

or a subclass of list:

class mylist(list):
  def get(self, index, default):
    try: return self[index]
    except IndexError: return default

which gives you the usage example:

abcd = mylist([1, 2, 3, 4])
item = abcd.get(5, 0)
Alex Martelli
+1  A: 

Personally I would not want to dedicate more than one line to this operation. As such I would go for something like item = len(abcd) > 5 and abcd[5] or 0.

A very important note on this technique, though, is that the element you want (abcd[5] in this case) must not evaluate to a boolean False value. If it does, the above statement will be evaluated to 0 in stead of the actual (False) value in the list (None, (), {}, etc).

Walter