Search code examples
pythonsortingradix

Radix sort python grammar


Find a radix sort code, but couldn't understand well for line "arr=[j for i in bucket_list for j in i]" I know it's sorting based on the bucket_list, but what j, i means in this line and what's the general way to write this function? Thanks.

def radix_sort(arr:List[int]):
    n = len(str(max(arr)))  
    for k in range(n):
        bucket_list=[[] for i in range(10)]
        for i in arr:
            bucket_list[i//(10**k)%10].append(i)
        arr=[j for i in bucket_list for j in i]
        print(arr)
    return arr

Solution

  • The line of code you're asking about has a list comprehension in it. It's equivalent to a two-level nested loop:

    arr = []
    for i in bucket_list:
        for j in i:
            arr.append(j)