Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Write load_list(name) that gives the list that is saved in a JSON file. If the file is missing or damaged, it gives an empty list. If the file holds valid JSON that is not a list (for example a number), it also gives an empty list. Test it with a missing file, a file with [1, 2], a file with oops, and a file with 5.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Catch both errors, and then check the type of what was loaded.
Check. The missing file gives []. [1, 2] is a list. oops is not valid JSON, so []. 5 is valid JSON but not a list, so [].
Answer: [] [1, 2] [] [].
Log in to join the discussion.
Loading…