439,930 Members | 2,018 Online
Need help? Post your question and get tips & solutions from a community of 439,930 IT Pros & Developers. It's quick & easy.

# getting the index while iterating through a list

 P: n/a Hi, While iterating through a list I'd like to know not just the current element, but also its index. Is there a better way than this: i = 0 newList = [] for element in aList: newList.append((i, element)) i += 1 Is there a more elegant way of doing this with for? And with map()? Thanks Jul 18 '05 #1
4 Replies

 P: n/a Fernando Rodríguez wrote: While iterating through a list I'd like to know not just the current element, but also its index. Is there a better way than this: i = 0 newList = [] for element in aList: newList.append((i, element)) i += 1 Is there a more elegant way of doing this with for? And with map()? Not with map. Use zip: newList = zip (range (len (aList)), aList) Greetings, Holger Jul 18 '05 #2

 P: n/a Fernando Rodríguez wrote: While iterating through a list I'd like to know not just the current element, but also its index. Is there a better way than this: i = 0 newList = [] for element in aList: newList.append((i, element)) i += 1 Is there a more elegant way of doing this with for? And with map()? aList = ["alpha", "beta", "gamma"] list(enumerate(aList)) [(0, 'alpha'), (1, 'beta'), (2, 'gamma')] Peter Jul 18 '05 #3

 P: n/a [Fernando Rodríguez] While iterating through a list I'd like to know not just the current element, but also its index. Is there a better way than this: i = 0 newList = [] for element in aList: newList.append((i, element)) i += 1 Is there a more elegant way of doing this with for? And with map()? Hi, Fernando. You may write something like: newList = [] for i, element in enumerate(aList): newList.append((i, element)) or even simpler: newList = list(enumerate(aList)) -- François Pinard http://www.iro.umontreal.ca/~pinard Jul 18 '05 #4

 P: n/a Fernando Rodríguez wrote: Hi, While iterating through a list I'd like to know not just the current element, but also its index. Is there a better way than this: i = 0 newList = [] for element in aList: newList.append((i, element)) i += 1 Is there a more elegant way of doing this with for? And with map()? Thanks Try enumerate: newList = [(i, element) for i, element in enumerate(aList)] from Python-Docs-2.3/lib/built-in-funcs.html: enumerate(iterable) Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from zero) and the corresponding value obtained from iterating over iterable. enumerate() is useful for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2, seq[2]), .... New in version 2.3. -- Steven Rumbalski news|at|rumbalski|dot|com Jul 18 '05 #5

### This discussion thread is closed

Replies have been disabled for this discussion.