3 Replies - 3101 Views - Last Post: 11 June 2011 - 10:30 PM Rate Topic: -----

#1 Achilles4689  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 43
  • Joined: 03-June 11

Striding for loop

Posted 11 June 2011 - 08:02 PM

Hey all,

Python noob student here. I need to have a striding for loop. How can you loop through a list on say every 3rd element?

Thanks,
Achilles

This post has been edited by atraub: 13 June 2011 - 12:06 PM
Reason for edit:: ftfy

Is This A Good Question/Topic? 0
  • +

Replies To: Striding for loop

#2 Brewer  Icon User is offline

  • Awesome
  • member icon

Reputation: 179
  • View blog
  • Posts: 1,044
  • Joined: 14-June 10

Re: Striding for loop

Posted 11 June 2011 - 09:12 PM

Unlike a for loop where you want to step by 1, you HAVE to include the min arg here. So if you want to iterate through a list for every 3rd element, starting at 0, ending at 10, you would use:

for i in range(0, 10, 3):

Was This Post Helpful? 2
  • +
  • -

#3 atraub  Icon User is offline

  • Pythoneer
  • member icon

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

Re: Striding for loop

Posted 11 June 2011 - 10:17 PM

The for-each style of loop would probably work a little better:

for eachElement in myList[::3]:

Was This Post Helpful? 2
  • +
  • -

#4 Achilles4689  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 43
  • Joined: 03-June 11

Re: Striding for loop

Posted 11 June 2011 - 10:30 PM

Thanks guys!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1