Note that there are some explanatory texts on larger screens.

plurals
  1. POPython loop through list and shorten by one
    text
    copied!<p>I have a list:</p> <pre><code> mylist = ['apple', 'orange', 'dragon', 'panda'] </code></pre> <p>I want to be able to is loop over the list, do something on each element and then remove the element. I tried this:</p> <pre><code>for l in mylist: print l list.remove(l) </code></pre> <p>but the my output is:</p> <pre><code>apple dragon </code></pre> <p><strong>EDIT</strong></p> <p>I actually want to be able to do some comparisons in the loop. So basically I want to be able to take each element, one-by-one, remove that element for the list and compare it against all the other elements in the list. The comparison is a little complex so I don't want to use list comprehension. And I want to be reducing the list by one each time until the list is empty and all elements have been compared with each other.</p> <p>What is the best way to get each element, work with it and remove it without skipping elements in the list?</p> <p>Any help, much appreciated.</p> <p><strong>REDIT</strong></p> <p>Just to make clear - the real point of this is to go through each element, which is a string fragment and match it with other fragments which have overlapping sequences on either end, thereby building up a complete sequence. The element being processed should be removed from the list prior to looping so that it isn't compared with itself, and the list should shrink by 1 element each processing loop.</p> <p>In the case a better list example would be:</p> <pre><code>mylist = ['apples and or', 'oranges have', 'in common', 'e nothing in c'] </code></pre> <p>to give:</p> <pre><code>'apples and oranges have nothing in common' </code></pre> <p>Apologies for not being clear from the outset, but it was a specific part of this larger problem that I was stuck on.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload