+ 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)
8 Respuestas
+ 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.
+ 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.
+ 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
+ 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
+ 2
Thank you Lothar and Per Bratthammar for the explanation, i understood the question.
0
0@pp
0
Hey any help am new here