0

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!

1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh wow, that's really cool. I really haven't seen this anywhere else before despite thinking that I know a lot of about python. Additionally, may I ask if this is application to dict and tuple?
I'm not sure. Try and see. :-)
No. It's not applicable to dict because dicts don't support slice indexing, and it's not applicable to tuple because tuples are immutable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.