Improved idiomatic python use by removing type comparisons and using isinstance
Removed unneeded .sort() and replaced with sorted()
Replaced range with lrange where needed