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
Use get() method to create a dictionary in Python from a list of elements.
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.
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.
Python Dictionary get() Method The get() method returns the value of the item with the specified key.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With