+ 1

If someone can explain me better this code below

X = [2, 1, 21, 13, 233, 144, 0, 3, 8, 5, 89, 34, 1, 55] for i in range(len(X)): for j in range(i+1 , len(X)): if X[i] >= X[j] : X[i],X[j] = X[j], X[i] print(X) This code sort the list with for loop but I don t understand why I need to add +1 to i , and this line of code : X[i],X[j] = X[j], X[i] if I understood right is swiping values.

17th Sep 2022, 4:38 PM
Andrei Macovei
Andrei Macovei - avatar
6 Answers
+ 3
+1 is there to not compare element at index i with itself
17th Sep 2022, 4:51 PM
Mateusz GoƂda
Mateusz GoƂda - avatar
+ 3
Andrei Macovei , here are 2 links to short tutorials from the community section: https://www.sololearn.com/learn/649/?ref=app https://www.sololearn.com/learn/701/?ref=app
17th Sep 2022, 6:39 PM
Lothar
Lothar - avatar
+ 2
Your guess with swapping values is right.
17th Sep 2022, 4:48 PM
Mateusz GoƂda
Mateusz GoƂda - avatar
+ 2
j = i+1 is next index to i Each value at index i is compared with next proceeding elements in the list. (Because Previous elements (0 to i) are already been searched, so skip.) Yes swaps.
17th Sep 2022, 4:52 PM
Jayakrishna 🇼🇳
+ 2
Thank you guys
17th Sep 2022, 4:57 PM
Andrei Macovei
Andrei Macovei - avatar
+ 2
For each index i of list X we check if element at i is greater than any element to the right. If it is we swap them.
17th Sep 2022, 4:58 PM
Mateusz GoƂda
Mateusz GoƂda - avatar