lists....order...

Erik Max Francis max at alcyone.com
Wed Oct 9 20:09:56 EDT 2002


gabor wrote:

> a = [1,2,3,4,5,6]
> for item in a:
>         print a
> 
> will print 1 2 3 4 5 6?
> in other words, is it guarantied that for a list the elements will be
> enumerated in their order?

Yes.  The ordering of elements within a list is significant; it won't
change on you unless you change it.

> 2. many times i use this construct:
> a = ["a","b","c","d"]
> for letter in a:
>         dosomething..
>         but now i really need the position of the letter in that list
>         so i need an x, for which a[x] = letter...
> 
> the only solution i could find:
> for index in range(len(a)):
>         letter = a[index]
> 
> is there a way to do that with the normal 'for letter in a' approach?

That's the customary approach.  Another version is:

	for element, index in zip(sequence, range(len(sequence))):
	    ...

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ When you talk to her / Talk to her
\__/ India Arie
    CSBuddy / http://www.alcyone.com/pyos/csbuddy/
 A Counter-Strike server log file monitor in Python.



More information about the Python-list mailing list