Add safe `.get` method to List

I understand that argument, but it’s not true that lists are only iterated. For example, I have a list of objects inside of a nested dictionary. I want to get a property of the first item in the list:

state = {"corp": {"hand": [{"title": "Sure Gamble"}]}}

state.get("corp", {}).get("hand", [])[0].get("title", "")

The .get() calls allow me to write a somewhat fluent and safe getter for the nested objects. But this blows up if the list is empty. To work around that, I have to store in a variable and then either check the length of the list or wrap the indexing in a try/except. If I’m using a variable index instead of a literal 0, then I need to use try/except because of negative indexes.

That’s a fairly complex example, but I think even the simple examples would benefit. For example, I want to look at the current item and the next item in a for loop. The following code blows up but with a safe get, it would do the “right” thing without blowing up:

lst = list(range(10))
for idx, item in enumerate(lst):
    next_item = lst[idx + 1]
    print(item, next_item)

I know the argument that there are ways around these situations (see the SO threads linked above) or that a simple if/then is easy to use, so we shouldn’t bloat the standard library. I think that such an argument exists for dictionaries as well. Why can’t people just use if "some_key" in d: ret = d["some_key"] else: ret = "default value"?

Given that dict.get() is both used and loved enough to make people want it for list, I see great value in adding it to list.

2 Likes