0
Why the output list is not ordered? Kindly Help.
Shouldn't the output list be in ascending order? https://code.sololearn.com/chV9uErJsltP/?ref=app
3 Respuestas
+ 3
1. Everything Anna said.
2. Why the output is not ordered: index(i) finds the first occurrence of i in the list. Here's how things happen in each step.
list = [1,2,3,4,5,6,7,8,9,10]
i=1. list.index(i)=0. list[0]=1
i=2. list.index(i)=1. list[1]=4
i=3. list.index(i)=2. list[2]=9
i=4. list.index(i)=1. list[1]=16 # problem
i=5. list.index(i)=4. list[4]=25
i=6. list.index(i)=5. list[5]=36
i=7. list.index(i)=6. list[6]=49
i=8. list.index(i)=7. list[7]=64
i=9. list.index(i)=2. list[2]=81 # problem
i=10. list.index(i)=9. list[9]=100
In particular, list[1] = 16, list[2] = 81, list[3] =4, and list[8] = 9 (the last two are never altered).
Your new list is
[1, 16, 81, 4, 25, 36, 49, 64, 9, 100]
+ 8
That's a strange way to iterate over a list 🤔
Why not use for i in range(len(list)): list[i] = ...? (btw, 'list' is a python keyword and shouldn't be used as a name for a variable)
+ 1
Kishalaya Saha you said "index(i) finds the first occurrence of i in the list."
I got it.
That solves the problem.
Thanks 😊👍