slicing the last second word in python
<p>i need to write a python script that will count the next-to-last word . my code is:</p>

<pre><code>with open('/tmp/values.txt') as f:
    for sentence in f:
        list_sentecne = [sen for sen in sentence.rstrip().split(' ')]

print (list_sentecne)
op = list_sentecne[-2:-2]
print (op)
</code></pre>

<p>output i got is:-</p>

<pre><code>['some', 'line', 'with', 'text']
[]
</code></pre>

<p>output that i need to get is :</p>

<pre><code>with
</code></pre>

<p>My idea is to use slicing , so i used [-2:-2] such that it will print 2nd word from last in the list but when i run the script, i am getting 'empty list' at the output.</p>

<p>Yo need to print from 2nd last element from list - </p>

<pre><code>&gt;&gt;&gt; list_sentecne = ['some', 'line', 'with', 'text']
&gt;&gt;&gt; op = list_sentecne[-2:]
&gt;&gt;&gt; print (op)
['with', 'text']
</code></pre>

<p>if only the 2nd last element </p>

<pre><code>&gt;&gt;&gt; list_sentecne = ['some', 'line', 'with', 'text']
&gt;&gt;&gt; op = list_sentecne[-2]
&gt;&gt;&gt; print (op)
'with'
</code></pre>

python python-2.7 python-3.x