Reputation: 47
I found this code online.
def quick_sort(items):
""" Implementation of quick sort """
if len(items) > 1:
pivot_index = len(items) / 2
smaller_items = []
larger_items = []
for i, val in enumerate(items):
if i != pivot_index:
if val < items[pivot_index]:
smaller_items.append(val)
else:
larger_items.append(val)
quick_sort(smaller_items)
quick_sort(larger_items)
items[:] = smaller_items + [items[pivot_index]] + larger_items
The one line that gives me trouble is the last one. I believe it's basic concatenation, however, when I change "items[:]" to "items", the algorithm fails. What is special about the [:] at the end of the list?
If anyone one can help, I would really appreciate. Thank you in advance!
Upvotes: 0
Views: 59
Reputation: 3222
This is in-place assignment, without replacing the list object with a new object. This way, the output is placed in the original list and can be read by the caller.
Upvotes: 2