Statement (un)equality
James Henderson
james at logicalprogression.net
Fri Feb 20 06:12:47 EST 2004
On Friday 20 February 2004 10:31 am, Adam Przybyla wrote:
> castle:/home/adam>python
> Python 2.3 (#3, Aug 4 2003, 16:43:33)
> [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>
> >>> [[y,x] for x,y in [1,2],[3,4]]
>
> [[2, 1], [4, 3]]
>
> >>> map(lambda x,y: [y,x], [1,2],[3,4])
>
> [[3, 1], [4, 2]]
>
> Why there is a difference?
Hi,
[[y,x] for x,y in [1,2],[3,4]]
is just the same as:
[[y,x] for (x,y) in ([1,2],[3,4])]
The list comprehension regards "[1,2],[3,4]" as a single argument (a tuple)
and "x,y" is also a tuple. "x,y" is assigned first [1,2] and then [3,4].
In the map statement "[1,2],[3,4]" are two different arguments. map's
signature allows for any number of iterables to be passed after the first
argument.
> How to make the same thing like in map
> statement?
zip() gives you the sequence of pairs you want to pass: (zip() is very
similar to map with None as the first arguemnt. The difference is how they
handle sequences of unequal length.)
>>> zip([1,2],[3,4])
[(1, 3), (2, 4)]
so:
[[y,x] for x,y in zip([1,2],[3,4])]
will match the behaviour of the map statement.
> Regards
> Adam Przybyla
James
--
James Henderson, Logical Progression Ltd.
http://www.logicalprogression.net/
http://sourceforge.net/projects/mailmanager/
More information about the Python-list
mailing list