find the kth smallest number in a list in python

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.py
def kth_smallest_number(nums, k):
    sorted_nums = sorted(nums)
    return sorted_nums[k-1]
93 chars
4 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.py
my_nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
print(kth_smallest_number(my_nums, 5))
83 chars
3 lines

This will output 4, since 4 is the 5th smallest number in the list.

gistlibby LogSnag