idiom for list looping

David Roberts d at vidr.cc
Wed Jul 29 05:31:47 EDT 2009


To the best of my knowledge the second way is more pythonic - the
first is a little too reminiscent of C. A couple of notes:
- you don't need the parentheses around "i, e"
- if you were going to use the first way it's better to use xrange
instead of range for iteration

--
David Roberts
http://da.vidr.cc/



On Wed, Jul 29, 2009 at 19:02, superpollo<user at example.net> wrote:
> hi clp.
>
> i want to get from here:
>
> nomi = ["one", "two", "three"]
>
> to here:
>
> 0 - one
> 1 - two
> 2 - three
>
> i found two ways:
>
> first way:
>
> for i in range(len(nomi)):
>    print i, "-", nomi[i]
>
> or second way:
>
> for (i, e) in enumerate(nomi):
>    print i, "-", e
>
> which one is "better"? is there a more pythonic way to do it?
>
> bye
>
> ps:
>
> max2 at 192.168.1.102:~/test$ python -V
> Python 2.3.4
> max2 at 192.168.1.102:~/test$ uname -a
> Linux fisso 2.4.24 #1 Thu Feb 12 19:49:02 CET 2004 i686 GNU/Linux
> max2 at 192.168.1.102:~/test$
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list