4 Replies - 750 Views - Last Post: 07 May 2011 - 10:50 AM Rate Topic: -----

#1 bnc  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 108
  • Joined: 18-March 10

for loop in python

Posted 05 May 2011 - 11:57 PM

how can we iterate for loop from the middle???

I have a code like this

line_num = 5
for line_num in range(len(lines)):
   print "line_num is",line_num



When I do this it is giving all the lines. But I want it to start from line number 5. How can We Do this??
Is This A Good Question/Topic? 0
  • +

Replies To: for loop in python

#2 runfaster  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 135
  • Joined: 23-January 09

Re: for loop in python

Posted 06 May 2011 - 12:19 AM

for loops in python are essentially for..each loops. Essentially, it is taking the range array and assigning the value of the first one to line_num.

luckily, range() is an overloaded function, and has another definition

int[] range(start,end)

Using this, you could do:

start_line = 5
for line_num in range(start_line,len(lines))
        do what you want to do with line_num with line_num



and be golden.

Hope this helps.

This post has been edited by runfaster: 06 May 2011 - 12:21 AM

Was This Post Helpful? 2
  • +
  • -

#3 bnc  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 108
  • Joined: 18-March 10

Re: for loop in python

Posted 06 May 2011 - 03:46 AM

Yes... it helps.. Thanks
Was This Post Helpful? 0
  • +
  • -

#4 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: for loop in python

Posted 06 May 2011 - 07:04 AM

You also have an increment option
for i in range(start, stop, increment):
    #Stuff



This will let you count by 2's, 3's, whatever. It opens some interesting possibilities :)
Was This Post Helpful? 1
  • +
  • -

#5 Nallo  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 163
  • View blog
  • Posts: 255
  • Joined: 19-July 09

Re: for loop in python

Posted 07 May 2011 - 10:50 AM

expanding on atraub post: When you don't care for the actual line number you don't need to index them. You can use sequence slicing:
>>> lines = ["a", "b", "c", "d", "e", "f"]
>>> for line in lines[4:]:
	print line
	
e
f
>>> for line in lines[3::2]:
	print line
	
d
f
>>> for line in lines[:3]:
	print line
	
a
b
c
>>> for line in lines[:-1]:
	print line
	
a
b
c
d
e
>>> for line in lines[-3:-1]:
	print line
	
d
e


Was This Post Helpful? 2
  • +
  • -

Page 1 of 1