I am trying to implement a partition function for quicksort in Python.
def partition(ls):
if len(ls) == 0:
return
pivot = ls[0]
i, j = 1
while j < len(ls):
if ls[j] <= pivot:
i += 1
temp = ls[i]
ls[i] = ls[j]
ls[j] = temp
j += 1
ls[0] = ls[i]
ls[i] = pivot
However, Python issues this error when I call quicksort.partition([1,2,3]).
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "quicksort.py", line 5, in partition
i, j = 1
TypeError: 'int' object is not iterable
What is this error saying? Of course, int objects are not iterable, but when did I ever iterate over an int object?
When you list multiple targets separated by commas on the left of an assignment, it tries to iterate over the right hand side and assign pieces to the pieces on the left. So if you do
x, y = (1, 2)then x will be 1 and y will be 2.If you want to make i and j both be 1, do
i = j = 1.(Note that this binds both variables to the same object. It’s fine for this case, but if you are assigning a mutable object (like
x = y = []) you should remember that both x and y will be pointing to the same list, so mutations will affect bothxandy.)