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>This happens because your list length changes every time you pop an element from the list. So if you want to use <code>pop</code> specifically, to remove the specified elements an easy and tricky way would be the following:</p>

<pre><code>&gt;&gt;&gt; nameList = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9']
&gt;&gt;&gt;
&gt;&gt;&gt; nameList.pop(nameList.index('n1'))
'n1'
&gt;&gt;&gt; nameList.pop(nameList.index('n4'))
'n4'
&gt;&gt;&gt; nameList.pop(nameList.index('n5'))
'n5'
&gt;&gt;&gt; nameList.pop(nameList.index('n6'))
'n6'
&gt;&gt;&gt; nameList.pop(nameList.index('n7'))
'n7'
&gt;&gt;&gt; nameList.pop(nameList.index('n8'))
'n8'
&gt;&gt;&gt; nameList.pop(nameList.index('n9'))
'n9'
&gt;&gt;&gt; nameList
['n2', 'n3']   
</code></pre>

<p>So as you can see every time we pop an element we specify its <code>index</code> so we don't have a problem that the list length changes - cause using <code>index</code> we will get the new index of the element! And as you can see the result will be: <code>['n2', 'n3']</code> as expected!</p>

python