3 Replies - 2735 Views - Last Post: 03 February 2011 - 05:17 PM Rate Topic: -----

#1 dilzniksan  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 35
  • Joined: 02-September 09

List Iteration Current Position

Posted 02 February 2011 - 10:31 PM

One off question here, please forgive me,
Given the following snippet
for word in list:


During each iteration is there a way to retrieve the current position in the list without incrementing a separate variable?
Is This A Good Question/Topic? 0
  • +

Replies To: List Iteration Current Position

#2 Nallo  Icon User is offline

  • D.I.C Regular
  • member icon

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

Re: List Iteration Current Position

Posted 03 February 2011 - 01:13 AM

You could use list.index(element) but that retruns the position of the first ocurence of element in the list, which is not necessarily the position you are looking for (when there are duplicate entries).

If you need an index variable without explicitly incrementing it yourself you can use enumerate:
for index, element in enumerate(list):


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: List Iteration Current Position

Posted 03 February 2011 - 07:41 AM

Enumerate is definitely the way to go. list.index(element) actually iterates through the list looking for that element, slowing down your program as a whole.

EDIT:
Why are you apologizing for asking a good question? :dontgetit:

This post has been edited by atraub: 03 February 2011 - 11:20 AM

Was This Post Helpful? 1
  • +
  • -

#4 dilzniksan  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 35
  • Joined: 02-September 09

Re: List Iteration Current Position

Posted 03 February 2011 - 05:17 PM

Thanks for the help guys.

@atraub: It seemed like a trivial (lazy) question to ask; honestly I was tired of googling.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1