for , ordering

Eric Brunel eric.brunel at pragmadev.com
Thu Jun 6 14:40:24 EDT 2002


gabor wrote:

> hi,
> 
> i have a list and i want to create a copy of it with a bit different
> objects... by now i have something like this:
> 
> objects1 = []
> objects2 = []
> .
> .
> .
> 
> for obj1 in objects1:
> objects2.append(obj2(obj1.x))
> 
> 
> 1. isn't there a more elegant way to do this?

Yep. Do:
objects2 = [obj2(obj1.x) for obj1 in objects1]
It's called a "list comprehension" and is the exact equivalent of your code 
above, just shorter. And it's almost more legible than the 'for' loop :-)

> 2. is that guaranteed that the for cycle iterates over the elemenst of
> the list in the correct order ( 0,1,2,3,4,....)?

Yep. Lists are ordered, so the 'for' loop or the list comprehension above 
are guaranteed to browse the list in order. Just to mention it, it wouldn't 
be the case with dictionaries, that reorder their entries for optimization 
purposes.

HTH
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com



More information about the Python-list mailing list