
Hi Austin, and welcome. On Mon, Jul 05, 2021 at 08:52:31PM -0500, Austin Graham wrote:
Essentially, I want to be able to perform a simple default get on a list if an index does not exist, similar to a dictionary.
Something like this: my_list = [1, 2, 3] my_list.get(10, 0) # returns 0 Can you explain *when* and *why* you would use that? Although lists use the same subscript syntax as dicts, they are used in very different ways. With dicts, it is very common to need to return the value of a key, if it exists, and use a default value if it doesn't. This is so common that Python supports no less than *four* ways of doing so: * dict.get method * dict.setdefault method * subclasses of dict with a `__missing__` method * collections.defaultdict over and above the usual two methods of checking for the key's existence, or using a try...except. With lists, we cannot say the same. Python is not a brand new language, and its not like we just haven't thought of this feature until now. There are two common uses for indexing: - iterating over each item in a list; - looking up a field in a record or struct by position (usually tuples). In neither case is it generally useful to say "item 10, or a default if there is no item 10". There may be occasional niche uses for such a thing, but it's not clear that such uses are generally useful enough to make it a list method. The most common use of lists involves iterating over each item in turn. There's no need to index it by position, and there's no chance of an index out of range error. Even slight variants, like walking through the list taking two items at a time, should never need get an out of range error. If you do get an index error, your code is buggy. When looking up an item in a tuple by position, if the index is out of range, the record is malformed and broken. It is true that this feature does get requested frequently, and *maybe* its time to accept that it would be useful and we should provide it. But since the people who would have to do the work don't think its useful (or else they would have already done it!) the initial steps to convince them are: - firstly, establish the use-cases for this get method; - explain why other alternatives are not sufficient; - decide whether it is just lists that have it, or tuples as well; - and what about strings and other sequences? And from there, we could go on to a PEP (Python Enhancement Proposal) and if accepted, one of the core devs would do the work. By the way, there is a third alternative to using try...except or checking the length: use a slice. my_list = [1, 2, 3] (my_list[10:11] or [default])[0] -- Steve