• 12
• 12
• 9
• 10
• 13

# Python: looping over a list

This topic is 3828 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello, In python, one can loop over a list (or a similar object) using this simple notation: for item in list: But let's say that you need to build a table that displays the current index, and the corresponding item inside the list. To do this, I adopt this much uglier notation:
for i in range(len(list)):
print i, ':', list

Is there a better workaround? I feel like I'm back in C++ again when I do this.

##### Share on other sites
list.index(item)

The only problem with that method is that it returns the lowest index for an item equivalent to the argument, so if your list contains multiple instances of a value, you have to track the last seen index. Why? Because index takes additional parameters:

list.index(item, i, j)

Returns the lowest k such that list[k] == item and i <= k <= j.

For the specific case of pairing the list items to the indices, however:

t = zip(list, range(len(list)))

##### Share on other sites
Quote:
 Original post by Oluseyilist.index(item)The only problem with that method is that it returns the lowest index for an item equivalent to the argument

Not to mention that finding an item in a list is a O(n) operation, which will slow down an iteration over a large list.

Quote:
 For the specific case of pairing the list items to the indices, however:t = zip(list, range(len(list)))

Plenty fast, but still ugly. The truth is that Python tends to err on the side of verbosity and only-one-way-to-do-it, eschewing the nifty little shortcuts of languages like Perl. The lack of a do/while construct is also frustrating, for example.

You deal, and you learn to take advantage of the tools that Python does offer, like zip, map, and lambda functions.

##### Share on other sites
for idx,item in enumerate(list):	print idx, ":", item

##### Share on other sites
My Python is a bit rusty, but how about like this:
for i, v in enumerate(['tic', 'tac', 'toe']):    print i, v
or
for (index, item) in enumerate(items):    print index, item
and consequently pairing indices with the values is just:
print enumerate(items)#ort = enumerate(items)
where enumerate acts as a generator generating the pairs. The enumerate has to be wrapped to the list element if you want to have the list right away as enumerate uses lazy evaluation and evaluates the pair one at a time when needed (like this list(enumerate(items)).

I think this is the simplest (and most efficient?) way of pairing values with their indices.

[EDIT]Kylotan was a quicker on the looping part. [smile] It's no good to read something, openg the reply dialog and go to lunch. [smile][/EDIT]