reverse range vs normal range when trying to remove items from a list using a for loop





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















For this for loop, this code:



lst = ['NORTH', 'SOUTH', 'EAST', 'EAST']

for num in range(0, len(lst) - 1):
if lst[num] == 'NORTH' and lst[num + 1] == 'SOUTH':
del lst[num]
del lst[num - 1]


I know it doesn't work because by deleting the items in the list, the len(lst) changes, however, why does this work:



for num in range(len(lst) - 1 , -1 , -1):
if lst[num] == 'SOUTH' and lst[num - 1] == 'NORTH':
del lst[num]
del lst[num - 1]


for this, aren't we also changing the list length? Why does the list length not matter in a reverse range?










share|improve this question




















  • 1





    By moving forward and removing list items, you are changing the indexes of the items that you have not processed yet. By moving backward and removing list items, you are changing the indexes of the items that you have processed.

    – DYZ
    Jan 3 at 7:32








  • 1





    @DYZ By deleting two items at a time, the second code is also subject to IndexError.

    – user9522315
    Jan 3 at 7:40











  • @iBot In theory, yes. But not in this case: deletion takes place only if the current item is SOUTH and the previous is NORTH; if the condition is true for num, it is not true for num-1.

    – DYZ
    Jan 3 at 7:42






  • 1





    @DYZ If in the first iteration, two elements are deleted, then in the second iteration lst[num] will fail (where num = len - 2). See my answer for an example.

    – user9522315
    Jan 3 at 7:44











  • @iBot Fair enough.

    – DYZ
    Jan 3 at 7:45


















1















For this for loop, this code:



lst = ['NORTH', 'SOUTH', 'EAST', 'EAST']

for num in range(0, len(lst) - 1):
if lst[num] == 'NORTH' and lst[num + 1] == 'SOUTH':
del lst[num]
del lst[num - 1]


I know it doesn't work because by deleting the items in the list, the len(lst) changes, however, why does this work:



for num in range(len(lst) - 1 , -1 , -1):
if lst[num] == 'SOUTH' and lst[num - 1] == 'NORTH':
del lst[num]
del lst[num - 1]


for this, aren't we also changing the list length? Why does the list length not matter in a reverse range?










share|improve this question




















  • 1





    By moving forward and removing list items, you are changing the indexes of the items that you have not processed yet. By moving backward and removing list items, you are changing the indexes of the items that you have processed.

    – DYZ
    Jan 3 at 7:32








  • 1





    @DYZ By deleting two items at a time, the second code is also subject to IndexError.

    – user9522315
    Jan 3 at 7:40











  • @iBot In theory, yes. But not in this case: deletion takes place only if the current item is SOUTH and the previous is NORTH; if the condition is true for num, it is not true for num-1.

    – DYZ
    Jan 3 at 7:42






  • 1





    @DYZ If in the first iteration, two elements are deleted, then in the second iteration lst[num] will fail (where num = len - 2). See my answer for an example.

    – user9522315
    Jan 3 at 7:44











  • @iBot Fair enough.

    – DYZ
    Jan 3 at 7:45














1












1








1


1






For this for loop, this code:



lst = ['NORTH', 'SOUTH', 'EAST', 'EAST']

for num in range(0, len(lst) - 1):
if lst[num] == 'NORTH' and lst[num + 1] == 'SOUTH':
del lst[num]
del lst[num - 1]


I know it doesn't work because by deleting the items in the list, the len(lst) changes, however, why does this work:



for num in range(len(lst) - 1 , -1 , -1):
if lst[num] == 'SOUTH' and lst[num - 1] == 'NORTH':
del lst[num]
del lst[num - 1]


for this, aren't we also changing the list length? Why does the list length not matter in a reverse range?










share|improve this question
















For this for loop, this code:



lst = ['NORTH', 'SOUTH', 'EAST', 'EAST']

for num in range(0, len(lst) - 1):
if lst[num] == 'NORTH' and lst[num + 1] == 'SOUTH':
del lst[num]
del lst[num - 1]


I know it doesn't work because by deleting the items in the list, the len(lst) changes, however, why does this work:



for num in range(len(lst) - 1 , -1 , -1):
if lst[num] == 'SOUTH' and lst[num - 1] == 'NORTH':
del lst[num]
del lst[num - 1]


for this, aren't we also changing the list length? Why does the list length not matter in a reverse range?







python python-3.x for-loop






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 3 at 7:34







tzyyyy

















asked Jan 3 at 7:29









tzyyyytzyyyy

83




83








  • 1





    By moving forward and removing list items, you are changing the indexes of the items that you have not processed yet. By moving backward and removing list items, you are changing the indexes of the items that you have processed.

    – DYZ
    Jan 3 at 7:32








  • 1





    @DYZ By deleting two items at a time, the second code is also subject to IndexError.

    – user9522315
    Jan 3 at 7:40











  • @iBot In theory, yes. But not in this case: deletion takes place only if the current item is SOUTH and the previous is NORTH; if the condition is true for num, it is not true for num-1.

    – DYZ
    Jan 3 at 7:42






  • 1





    @DYZ If in the first iteration, two elements are deleted, then in the second iteration lst[num] will fail (where num = len - 2). See my answer for an example.

    – user9522315
    Jan 3 at 7:44











  • @iBot Fair enough.

    – DYZ
    Jan 3 at 7:45














  • 1





    By moving forward and removing list items, you are changing the indexes of the items that you have not processed yet. By moving backward and removing list items, you are changing the indexes of the items that you have processed.

    – DYZ
    Jan 3 at 7:32








  • 1





    @DYZ By deleting two items at a time, the second code is also subject to IndexError.

    – user9522315
    Jan 3 at 7:40











  • @iBot In theory, yes. But not in this case: deletion takes place only if the current item is SOUTH and the previous is NORTH; if the condition is true for num, it is not true for num-1.

    – DYZ
    Jan 3 at 7:42






  • 1





    @DYZ If in the first iteration, two elements are deleted, then in the second iteration lst[num] will fail (where num = len - 2). See my answer for an example.

    – user9522315
    Jan 3 at 7:44











  • @iBot Fair enough.

    – DYZ
    Jan 3 at 7:45








1




1





By moving forward and removing list items, you are changing the indexes of the items that you have not processed yet. By moving backward and removing list items, you are changing the indexes of the items that you have processed.

– DYZ
Jan 3 at 7:32







By moving forward and removing list items, you are changing the indexes of the items that you have not processed yet. By moving backward and removing list items, you are changing the indexes of the items that you have processed.

– DYZ
Jan 3 at 7:32






1




1





@DYZ By deleting two items at a time, the second code is also subject to IndexError.

– user9522315
Jan 3 at 7:40





@DYZ By deleting two items at a time, the second code is also subject to IndexError.

– user9522315
Jan 3 at 7:40













@iBot In theory, yes. But not in this case: deletion takes place only if the current item is SOUTH and the previous is NORTH; if the condition is true for num, it is not true for num-1.

– DYZ
Jan 3 at 7:42





@iBot In theory, yes. But not in this case: deletion takes place only if the current item is SOUTH and the previous is NORTH; if the condition is true for num, it is not true for num-1.

– DYZ
Jan 3 at 7:42




1




1





@DYZ If in the first iteration, two elements are deleted, then in the second iteration lst[num] will fail (where num = len - 2). See my answer for an example.

– user9522315
Jan 3 at 7:44





@DYZ If in the first iteration, two elements are deleted, then in the second iteration lst[num] will fail (where num = len - 2). See my answer for an example.

– user9522315
Jan 3 at 7:44













@iBot Fair enough.

– DYZ
Jan 3 at 7:45





@iBot Fair enough.

– DYZ
Jan 3 at 7:45












1 Answer
1






active

oldest

votes


















0














As DYZ said in comments, with reverse indexing, you're changing the indices of items that you have already processed, so the code won't fail when it continues.



However, it seems you're lucky with the input, since you're deleting two items at once. If you change the input list to this one, it will still fail with an IndexError.



lst = ['EAST', 'EAST', 'NORTH', 'SOUTH']


If you want to perform list manipulation like this, you're better off with a while loop.



num = 0
while num < len(lst) - 1:
if lst[num] == 'NORTH' and lst[num + 1] == 'SOUTH':
del lst[num]
del lst[num - 1]
else:
num += 1





share|improve this answer
























  • Hi! Thanks for the answer. However, is it possible to elaborate further on this line? 'with reverse indexing, you're changing the indices of items that you have already processed, so the code won't fail when it continues.' according to my list, by moving forward, if i delete index 0 and index 1, i understand the remaining list won't work because i left 2 items in the list which are now 0 and 1. But moving backwards, if i delete the same 2 items, won't the result be the same? The index of the remaining 2 will be 0 and 1?

    – tzyyyy
    Jan 5 at 1:38













  • Also, why would the list fail if it were 2 items compared to 1? In both cases, the index of the remaining items would change wouldn't it?

    – tzyyyy
    Jan 5 at 1:41











  • @tzyyyy If you do it in the reverse way, you're processing, say for example, 5,4,3,2,1,0. Assume you deleted 3 and move on, the previous 5 and 4 become 4 and 3, but you're going to process 2,1,0 which are unaffected. Deleting items always reduce the index of "later items" (in the list), so if you're moving from big index to small index, it isn't much of a problem.

    – iBug
    Jan 6 at 5:53














Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54018053%2freverse-range-vs-normal-range-when-trying-to-remove-items-from-a-list-using-a-fo%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














As DYZ said in comments, with reverse indexing, you're changing the indices of items that you have already processed, so the code won't fail when it continues.



However, it seems you're lucky with the input, since you're deleting two items at once. If you change the input list to this one, it will still fail with an IndexError.



lst = ['EAST', 'EAST', 'NORTH', 'SOUTH']


If you want to perform list manipulation like this, you're better off with a while loop.



num = 0
while num < len(lst) - 1:
if lst[num] == 'NORTH' and lst[num + 1] == 'SOUTH':
del lst[num]
del lst[num - 1]
else:
num += 1





share|improve this answer
























  • Hi! Thanks for the answer. However, is it possible to elaborate further on this line? 'with reverse indexing, you're changing the indices of items that you have already processed, so the code won't fail when it continues.' according to my list, by moving forward, if i delete index 0 and index 1, i understand the remaining list won't work because i left 2 items in the list which are now 0 and 1. But moving backwards, if i delete the same 2 items, won't the result be the same? The index of the remaining 2 will be 0 and 1?

    – tzyyyy
    Jan 5 at 1:38













  • Also, why would the list fail if it were 2 items compared to 1? In both cases, the index of the remaining items would change wouldn't it?

    – tzyyyy
    Jan 5 at 1:41











  • @tzyyyy If you do it in the reverse way, you're processing, say for example, 5,4,3,2,1,0. Assume you deleted 3 and move on, the previous 5 and 4 become 4 and 3, but you're going to process 2,1,0 which are unaffected. Deleting items always reduce the index of "later items" (in the list), so if you're moving from big index to small index, it isn't much of a problem.

    – iBug
    Jan 6 at 5:53


















0














As DYZ said in comments, with reverse indexing, you're changing the indices of items that you have already processed, so the code won't fail when it continues.



However, it seems you're lucky with the input, since you're deleting two items at once. If you change the input list to this one, it will still fail with an IndexError.



lst = ['EAST', 'EAST', 'NORTH', 'SOUTH']


If you want to perform list manipulation like this, you're better off with a while loop.



num = 0
while num < len(lst) - 1:
if lst[num] == 'NORTH' and lst[num + 1] == 'SOUTH':
del lst[num]
del lst[num - 1]
else:
num += 1





share|improve this answer
























  • Hi! Thanks for the answer. However, is it possible to elaborate further on this line? 'with reverse indexing, you're changing the indices of items that you have already processed, so the code won't fail when it continues.' according to my list, by moving forward, if i delete index 0 and index 1, i understand the remaining list won't work because i left 2 items in the list which are now 0 and 1. But moving backwards, if i delete the same 2 items, won't the result be the same? The index of the remaining 2 will be 0 and 1?

    – tzyyyy
    Jan 5 at 1:38













  • Also, why would the list fail if it were 2 items compared to 1? In both cases, the index of the remaining items would change wouldn't it?

    – tzyyyy
    Jan 5 at 1:41











  • @tzyyyy If you do it in the reverse way, you're processing, say for example, 5,4,3,2,1,0. Assume you deleted 3 and move on, the previous 5 and 4 become 4 and 3, but you're going to process 2,1,0 which are unaffected. Deleting items always reduce the index of "later items" (in the list), so if you're moving from big index to small index, it isn't much of a problem.

    – iBug
    Jan 6 at 5:53
















0












0








0







As DYZ said in comments, with reverse indexing, you're changing the indices of items that you have already processed, so the code won't fail when it continues.



However, it seems you're lucky with the input, since you're deleting two items at once. If you change the input list to this one, it will still fail with an IndexError.



lst = ['EAST', 'EAST', 'NORTH', 'SOUTH']


If you want to perform list manipulation like this, you're better off with a while loop.



num = 0
while num < len(lst) - 1:
if lst[num] == 'NORTH' and lst[num + 1] == 'SOUTH':
del lst[num]
del lst[num - 1]
else:
num += 1





share|improve this answer













As DYZ said in comments, with reverse indexing, you're changing the indices of items that you have already processed, so the code won't fail when it continues.



However, it seems you're lucky with the input, since you're deleting two items at once. If you change the input list to this one, it will still fail with an IndexError.



lst = ['EAST', 'EAST', 'NORTH', 'SOUTH']


If you want to perform list manipulation like this, you're better off with a while loop.



num = 0
while num < len(lst) - 1:
if lst[num] == 'NORTH' and lst[num + 1] == 'SOUTH':
del lst[num]
del lst[num - 1]
else:
num += 1






share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 3 at 7:42







user9522315




















  • Hi! Thanks for the answer. However, is it possible to elaborate further on this line? 'with reverse indexing, you're changing the indices of items that you have already processed, so the code won't fail when it continues.' according to my list, by moving forward, if i delete index 0 and index 1, i understand the remaining list won't work because i left 2 items in the list which are now 0 and 1. But moving backwards, if i delete the same 2 items, won't the result be the same? The index of the remaining 2 will be 0 and 1?

    – tzyyyy
    Jan 5 at 1:38













  • Also, why would the list fail if it were 2 items compared to 1? In both cases, the index of the remaining items would change wouldn't it?

    – tzyyyy
    Jan 5 at 1:41











  • @tzyyyy If you do it in the reverse way, you're processing, say for example, 5,4,3,2,1,0. Assume you deleted 3 and move on, the previous 5 and 4 become 4 and 3, but you're going to process 2,1,0 which are unaffected. Deleting items always reduce the index of "later items" (in the list), so if you're moving from big index to small index, it isn't much of a problem.

    – iBug
    Jan 6 at 5:53





















  • Hi! Thanks for the answer. However, is it possible to elaborate further on this line? 'with reverse indexing, you're changing the indices of items that you have already processed, so the code won't fail when it continues.' according to my list, by moving forward, if i delete index 0 and index 1, i understand the remaining list won't work because i left 2 items in the list which are now 0 and 1. But moving backwards, if i delete the same 2 items, won't the result be the same? The index of the remaining 2 will be 0 and 1?

    – tzyyyy
    Jan 5 at 1:38













  • Also, why would the list fail if it were 2 items compared to 1? In both cases, the index of the remaining items would change wouldn't it?

    – tzyyyy
    Jan 5 at 1:41











  • @tzyyyy If you do it in the reverse way, you're processing, say for example, 5,4,3,2,1,0. Assume you deleted 3 and move on, the previous 5 and 4 become 4 and 3, but you're going to process 2,1,0 which are unaffected. Deleting items always reduce the index of "later items" (in the list), so if you're moving from big index to small index, it isn't much of a problem.

    – iBug
    Jan 6 at 5:53



















Hi! Thanks for the answer. However, is it possible to elaborate further on this line? 'with reverse indexing, you're changing the indices of items that you have already processed, so the code won't fail when it continues.' according to my list, by moving forward, if i delete index 0 and index 1, i understand the remaining list won't work because i left 2 items in the list which are now 0 and 1. But moving backwards, if i delete the same 2 items, won't the result be the same? The index of the remaining 2 will be 0 and 1?

– tzyyyy
Jan 5 at 1:38







Hi! Thanks for the answer. However, is it possible to elaborate further on this line? 'with reverse indexing, you're changing the indices of items that you have already processed, so the code won't fail when it continues.' according to my list, by moving forward, if i delete index 0 and index 1, i understand the remaining list won't work because i left 2 items in the list which are now 0 and 1. But moving backwards, if i delete the same 2 items, won't the result be the same? The index of the remaining 2 will be 0 and 1?

– tzyyyy
Jan 5 at 1:38















Also, why would the list fail if it were 2 items compared to 1? In both cases, the index of the remaining items would change wouldn't it?

– tzyyyy
Jan 5 at 1:41





Also, why would the list fail if it were 2 items compared to 1? In both cases, the index of the remaining items would change wouldn't it?

– tzyyyy
Jan 5 at 1:41













@tzyyyy If you do it in the reverse way, you're processing, say for example, 5,4,3,2,1,0. Assume you deleted 3 and move on, the previous 5 and 4 become 4 and 3, but you're going to process 2,1,0 which are unaffected. Deleting items always reduce the index of "later items" (in the list), so if you're moving from big index to small index, it isn't much of a problem.

– iBug
Jan 6 at 5:53







@tzyyyy If you do it in the reverse way, you're processing, say for example, 5,4,3,2,1,0. Assume you deleted 3 and move on, the previous 5 and 4 become 4 and 3, but you're going to process 2,1,0 which are unaffected. Deleting items always reduce the index of "later items" (in the list), so if you're moving from big index to small index, it isn't much of a problem.

– iBug
Jan 6 at 5:53






















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54018053%2freverse-range-vs-normal-range-when-trying-to-remove-items-from-a-list-using-a-fo%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

MongoDB - Not Authorized To Execute Command

in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

Npm cannot find a required file even through it is in the searched directory