In the mentioned link, python lists medical insurance costs project, we are asked to create medical records 2D list where the price is the first dimension, and names are in the second one.
Later we’re asked to count the amount of times patient named Paul is listed in the records.
Is there anyway to scan the 2nd dimension using lst.count() method?
Same with lst.sort()? Can’t I sort it based on the 2nd dimension?
You might’ve realised but 2D lists in Python can be a pain to work with, I’d avoid the nesting if you can. I don’t think there’s a high-level way to get at this data, you basically have to loop through and access the second element which prevents you from using .count() directly.
There might be tricks to make this more convenient with map to access elements or zip to transpose the data but at the end of the day it’s the same task (they’re tools you probably won’t come across for a while but if you’re curious you can search around for similar problems).
Does the definition for .count() uses a simple for statement that loops through the list?
Because in this situation there’s really no reason why not to create a function like def count_nD(lst, dimension): that just nest loops to get search access to higher dimensions in my opinion.
Yes you could certainly write your own function for this task which would probably be far more convenient in the future should you require it again.
In standard CPython at least the answer for does the .count method use loops is technically yes it uses a loop but for built-in types like a list the methods are actually implemented in C so there’s no simple way to access this implementation.
Implementation details ahead, possibly interesting but probably not useful to you...
Long story short not matter how you accessed it you’d first need to look up each individual nested list object from the first outer list and then look up the 2nd element from that inner list object. There’s no direct connection otherwise.