To find the kth smallest number in a list, one approach is to sort the list and return the k-1th index. Here is a code snippet showing this approach:
main.py93 chars4 lines
This function takes in a list of nums
and an integer k
, and returns the kth smallest number in nums
. sorted()
is used to sort the list in ascending order, and then the k-1th index is returned since array indexing starts at 0 in Python.
To use this function, simply call it with a list and a k value. For example:
main.py83 chars3 lines
This will output 4
, since 4 is the 5th smallest number in the list.
gistlibby LogSnag