-3

why this code doesn't work at all?:

l3 = [1, 7, 10, 16, 5, 6, 13, 20]
for i in range(len(l3)):   
    l3[i], l3[l3.index(min(l3[i:]), i)] = l3[l3.index(min(l3[i:]), i)], l3[i]
print(l3)

However when we change the order - it works well:

l3 = [1, 7, 10, 16, 5, 6, 13, 20]
for i in range(len(l3)):
    l3[l3.index(min(l3[i:]), i)], l3[i] = l3[i], l3[l3.index(min(l3[i:]), i)]
print(l3)
Mad Physicist
  • 95,415
  • 23
  • 151
  • 231
  • 1
    The `l3.index(min(l3[i:]), i)` on the left-hand side of the assignment is computed after `l3[i]` is already assigned. Instead, compute the index, store it in some variable (such as `j = l3.index(min(l3[i:]), i)`), and then use that variable. – Dennis Jun 01 '22 at 17:20
  • 1
    You have an indentation error if nothing else – Mad Physicist Jun 01 '22 at 17:21
  • 1
    Related: [Multiple assignment and evaluation order in Python](https://stackoverflow.com/questions/8725673/multiple-assignment-and-evaluation-order-in-python). – jarmod Jun 01 '22 at 17:25
  • 2
    At the very least, call `l3.index` *once* and save the result for reuse in the actual swap. What you have right now is unreadable at best. – chepner Jun 01 '22 at 17:25
  • I feel like SO has been full of people asking the *exact* same questions about selection sort for the past few days. Y'all need to form a study group so you aren't duplicating each others' efforts. :) – Samwise Jun 01 '22 at 17:28
  • @Samwise. Summer semester just started, and they're using SO as the study area unfortunately. – Mad Physicist Jun 01 '22 at 17:30

0 Answers0