deleting (POPing) specific elements from list
<p>I am doing book exercise on pop() function in Python (3.5). The instructions are to delete elements from the list using pop(). From the list below, I want to delete n1, n4, n5, n6, n7, n8, n9. Below code works, but very practical) and I don't understand why specific index works only up until [5]. With out using loops (I'm not there yet), what is the proper way of poping specific elements from the list? </p>

<pre><code>nameList = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9']
print('I can only invite two people to dinner...')

print('Sorry, but ', nameList.pop(0).title(), ' will not be invited to 
       dinner') 
print('Sorry, but ', nameList.pop(3).title(), ' will not be invited to
      dinner')
print('Sorry, but ', nameList.pop(4).title(), ' will not be invited to
      dinner') 
print('Sorry, but ', nameList.pop(5).title(), ' will not be invited to
      dinner') 
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
      dinner')
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
      dinner')
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
      dinner') 
</code></pre>

<p>The output is: </p>

<pre><code>I can only invite two people to dinner...
('Sorry, but ', 'N1', ' will not be invited todinner')
('Sorry, but ', 'N5', ' will not be invited to dinner')
('Sorry, but ', 'N7', ' will not be invited to dinner')
('Sorry, but ', 'N9', ' will not be invited to  dinner')
('Sorry, but ', 'N8', ' will not be invited to  dinner')
('Sorry, but ', 'N6', ' will not be invited to   dinner')
('Sorry, but ', 'N4', ' will not be invited to   dinner')
</code></pre>

<p>Lets see it:</p>

<p>At first your list has 9 elements. You remove the first with <code>pop(0)</code> so now you have a list with 8 elements namely:</p>

<pre><code>['n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9']
</code></pre>

<p>Not you remove the 3th elelemnt from this 'new' list, which is <code>n5</code> (remember indexing starts from 0)</p>

<p>And so on ...</p>

<p>After each remove the list will simply be shorter, so even after the first remove there won be an element at the eighth position to remove (this happens after pop(5) in your case).</p>

<p>There is no 'general' way of removing elements from a list, but note that lists are mutable variables.</p>

python