0

I'm currently studying over algorithms and my book uses Python for the code examples, but I'm not much of a Python expert. For quicksort, I ran into this code where I don't understand some of the lines:

def quickSort(array):
    if len(array) < 2:
        return array;
    else:
        pivot = array[0];
        less = [i for i in array [1:] if i <= pivot]
        greater = [i for i in array [1:] if i > pivot]
        return quickSort(less) + [pivot] + quickSort(greater);

print (quickSort([1, 16, 22, 15, 7, 60, 65, 23]))

for the definition of less, what is the meaning of the snippet [i for i in array [1:] if i <= pivot] I understand that loops in Python go like "for book in books", but I don't understand what they mean by "i for i in array" and why is it all enclosed in square brackets?

Then at the return statement, why is [pivot] also enclosed in brackets?

I tried googling it but I didn't get any proper results, since I just don't know the names for this syntax.

Thank you!

  • `[1:]` is called slicing, the bracket thing you are asking about is a `list comprehension` – Joran Beasley May 26 '20 at 06:17
  • 1
    See "list comprehension" in the cited duplicate. You can look up any tutorial on the topic -- now that you know its name. – Prune May 26 '20 at 06:18

0 Answers0