Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

how to iterate a specific number of times on a for loop list?

$
0
0
Hi,

I have a FOR loop list consisting of 15 rows. But how can I make this FOR loop list stop at row 5?

# http://www.doughellmann.com/PyMOTW/itertools/index.html#module-itertools

from itertools import islice, count

j = 1

lines = open('machines.txt', 'r').readlines()

# while (j > 0):

for line in lines:
    print '%2s        %s' % (j, line)
    j = j+1





I tried Doug Hellmann's islice() example but couldn't figure out how to integrate this into my code?
from itertools import *

print 'Stop at 5:'
for i in islice(count(), 5):
    print i



Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>