Order guaranteed with list comprehension?

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri May 16 05:21:40 EDT 2003


Harald Massa <cpl.19.ghum at spamgourmet.com> wrote in 
news:Xns937D7008473Fcpl19ghumspamgourmet at 62.153.159.134:

>>>> maedels=['Sandra', 'Miriam', 'Katja', 'Melanie']
>>>> my=[a for a in maedels if a[0]=="M"]
>>>> my
> ['Miriam', 'Melanie']
> 
> I select part of a list ... the names starting with "M"
> 
> the comprehended list is in the same order as the basic list.
> 
> Is this guaranteed by specification or just a lucky point in the current 
> Python implementation?
> 

Iterating over a list always goes through the list in order. It doesn't 
matter whether you write it as a list comprehension or use an explicit for 
loop, either way 'for a in maedels' will go through the list elements in 
order.

Tuples also preserve order, dictionaries don't.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list