+ 8

Doubt

Why output is 1,3,5,6,7 Code:- a = [0,1,2,3,4,5,6,7] for i in range(3): a.pop(i) print(a)

16th Jul 2024, 4:12 PM
You
You - avatar
8 Respostas
+ 11
You , the reason for the behavior of the output is the fact, that removing an item from the list will cause a changing in the relation of index and value. see the outputs here (first line is the index number): 0 1 2 3 4 5 6 7 << indexes !!! [0, 1, 2, 3, 4, 5, 6, 7] original list output [1, 2, 3, 4, 5, 6, 7] after deleting index 0 [1, 3, 4, 5, 6, 7] after deleting index 1 [1, 3, 5, 6, 7] after deleting index 2 to fix the issue, we can use a reversed index sequence, that starts with the highest index number like: ... ... reversed(range(3) ... ... >> an other hint for you is to use *4 spaces* for indentation. this is recommended by the python style guidelines, and gives a quite good readability.
16th Jul 2024, 6:06 PM
Lothar
Lothar - avatar
+ 11
Try indenting the print statement to put it inside the loop. Then you can see the progression how it alters a[] and shifts element positions at each step.
16th Jul 2024, 4:37 PM
Brian
Brian - avatar
+ 4
Thank you Brian and Lothar, you guys are too intelligent 🧠🤓
17th Jul 2024, 2:32 AM
You
You - avatar
+ 4
Hi, You can 'pop' elements in order from left to right from using negative index to avoid unexpected results: https://sololearn.com/compiler-playground/c5S696qw41fb/?ref=app
18th Jul 2024, 3:45 AM
Per Bratthammar
Per Bratthammar - avatar
+ 3
I thought about what a solution could look like, even if the index positions that are to be deleted are not in an ordered sequence. Assume that the index values ​​that have to be deleted do not come from a range (ordered sequence) but from a data structure where they are in a random order. To do this, the elements of the data structure can be sorted in descending order. If this data structure is iterated over, it is ensured that the order of deletion begins at the end of the data structure. https://sololearn.com/compiler-playground/ch0k0iSRTeh8/?ref=app
18th Jul 2024, 11:33 AM
Lothar
Lothar - avatar
+ 2
Thank you Lothar and Per Bratthammar for the explanation, i understood the question.
19th Jul 2024, 9:45 AM
You
You - avatar
0
0@pp
17th Jul 2024, 10:05 PM
Hậu Dương Đình
0
Hey any help am new here
18th Jul 2024, 3:40 AM
Mustapha junior
Mustapha junior - avatar