Why does Python handle a KeyError differently than an IndexError (in this case)? -
i trying out various one-line solutions problem of defining variable if not exist , noticed python handles dicts , lists/tuples differently. these errors seem entirely parallel me, i'm confused why there discrepancy.
dictionary keyerror handling
existing_dict = {"spam": 1, "eggs": 2} existing_dict["foo"] = existing_dict["foo"] if not keyerror else 3
returns {"spam": 1, "eggs": 2, "foo": 3}
notice i'm referencing non-existing key in both left , right hand sides; python has no problem handling keyerror in either clause appears.
list indexerror handling (also true tuples)
existing_list = ["spam","eggs"] existing_list[2] = existing_list[2] if not indexerror else ["foo"]
returns indexerror: list assignment index out of range
it's not difficult @ around specific error (answer here), i'm curious why there difference in these cases. in both situations, there seems error in both assignee/assignment clauses 1 "if not" error catch.
in both cases, keyerror
, indexerror
just classes , both true:
>>> bool(keyerror) true >>> bool(indexerror) true
all class objects test true in python, see truth value testing.
you cannot use conditional expressions test exception; both examples, else
value picked always, assigned; tests equivalent to:
existing_dict["foo"] = 3 existing_list[2] = ["foo"]
you'd use exception handling instead, or use length test.
the exception caused because assignment list indexes only works if index exists:
>>> empty = [] >>> empty[0] = none traceback (most recent call last): file "<stdin>", line 1, in <module> indexerror: list assignment index out of range
this difference in how dictionary , list works; lists can append to, grow number of indices. cannot dictionary (there no order), add new key-value pair need assign it. on other hand, if lists supported arbitrary index assignment, happen indices in between? if list empty assigned index 42; happens indices 0-41?
either catch exception try
/except
:
try: existing_list[2] = "foo" except indexerror: existing.append('foo')
this replaces existing value @ index 2, or appends if index doesn't yet exist.
you try test length:
if len(existing_list) <= 3: existing_list.append('foo')
and it'll appended if there not yet @ least 3 elements.
for dictionaries, test key:
if 'foo' not in existing_dict: existing_dict['foo'] = 3
Comments
Post a Comment