moving items in a list
andy
andy at eastonwest.co.uk
Fri Jan 10 16:41:59 EST 2003
On Tuesday 07 Jan 2003 9:50 pm, Skip Montanaro wrote:
> ...
> Mark> j = i - 1
> Mark> swap_with = l[j]
> Mark> l[i] = swap_with
> Mark> l[j] = item
> ...
>
> How about
>
> l[i-1], l[i] = l[i], l[i-1]
>
> ? It's visually simpler than using a temporary variable and captures the
> sentiment better I think.
>
> Skip
Ug? You just broke one of my longest-standing programming diktats, ever since
my college tutor asked us 'anybody know a way to swap the contents of two
variables?'
Everybody started off saying something like:
a=b
b=a
and then realised how stupid that was...
And that was, er, about 20 years ago. I've never seen a language that could
do that any better without a 'swap' function.
a,b=b,a # how much more obvious can you get?
Just goes to show that you need to talk to people about Python - just applying
what you already know from (even 20+ years of) programming experience IS NOT
ENOUGH. That would never have occurred to me...
-andyj
More information about the Python-list
mailing list