Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't list have safe "get" method like dictionary?

Why doesn't list have a safe "get" method like dictionary?

>>> d = {'a':'b'} >>> d['a'] 'b' >>> d['c'] KeyError: 'c' >>> d.get('c', 'fail') 'fail'  >>> l = [1] >>> l[10] IndexError: list index out of range 
like image 547
Mikhail M. Avatar asked Feb 26 '11 07:02

Mikhail M.


People also ask

Does Python list have get method?

Use get() method to create a dictionary in Python from a list of elements.

Can a list have dictionary Python?

Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.

How do I find an item in a list Python?

To find an element in the list, use the Python list index() method, The index() is an inbuilt Python method that searches for an item in the list and returns its index. The index() method finds the given element in the list and returns its position.

What is .get in Python?

Python Dictionary get() Method The get() method returns the value of the item with the specified key.


2 Answers

Ultimately it probably doesn't have a safe .get method because a dict is an associative collection (values are associated with names) where it is inefficient to check if a key is present (and return its value) without throwing an exception, while it is super trivial to avoid exceptions accessing list elements (as the len method is very fast). The .get method allows you to query the value associated with a name, not directly access the 37th item in the dictionary (which would be more like what you're asking of your list).

Of course, you can easily implement this yourself:

def safe_list_get (l, idx, default):   try:     return l[idx]   except IndexError:     return default 

You could even monkeypatch it onto the __builtins__.list constructor in __main__, but that would be a less pervasive change since most code doesn't use it. If you just wanted to use this with lists created by your own code you could simply subclass list and add the get method.

like image 163
Nick Bastin Avatar answered Sep 27 '22 22:09

Nick Bastin


This works if you want the first element, like my_list.get(0)

>>> my_list = [1,2,3] >>> next(iter(my_list), 'fail') 1 >>> my_list = [] >>> next(iter(my_list), 'fail') 'fail' 

I know it's not exactly what you asked for but it might help others.

like image 27
Jake Avatar answered Sep 27 '22 21:09

Jake