Post details: reversing a list

10/22/06

Permalink 02:32:35 pm, Categories: Python, 112 words   English (US)

reversing a list

I've always found the reverse() method of a list rather wierd because it reverses the list in place. I just found out about reversing via slicing:

>>> f=['foo', 'bar', 'baz']
>>> f[::-1]
['baz', 'bar', 'foo']
>>> f='hello'
>>> f[::-1]
'olleh'

There is also a new builtin function in 2.4 called reversed(), which returns an iterator, and is more efficient for large lists:

>>> f=['foo', 'bar', 'baz']
>>> for x in reversed(f):
...   print x
... 
baz
bar
foo

And yet another (ugly) method shown to me by a coworker:

>>> f=['foo', 'bar', 'baz']
>>> reduce(lambda x,y: [y] + ((type(x) == type([]))
...        and x or [x]), f)
['baz', 'bar', 'foo']

Hmm, Python seems to be moving towards TMTOWTDI.

Comments, Pingbacks:

No Comments/Pingbacks for this post yet...

Leave a comment:

 
 

This is a captcha-picture. It is used to prevent mass-access by robots. (see: www.captcha.net)

You must read and type the 5 chars within 0..9 and A..F, and submit the form.

  

Oh no, I cannot read this. Please, generate a

Viraj's Weblog

Donate to keep this site going!

Amount USD $

June 2011
Mon Tue Wed Thu Fri Sat Sun
<<  <   >  >>
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30      

Search

Categories


Misc

Syndicate this blog XML

What is RSS?

powered by
b2evolution