Noob questions about Python

Adam Atlas adam at atlas.st
Wed Oct 17 16:01:48 EDT 2007


On Oct 17, 3:37 pm, Ixiaus <parnel... at comcast.net> wrote:
> I have recently (today) just started learning/playing with Python. So
> far I am excited and impressed (coming from PHP background).
>
> I have a few questions regarding Python behavior...
>
> val = 'string'
> li = list(val)
> print li.reverse()
>
> returns nothing, but,
>
> val = 'string'
> li = list(val)
> li.reverse()
> print li
>
> returns what I want. Why does Python do that?

Because list.reverse() modifies a list, it doesn't create and return a
new one.

A common idiom for returning a reversed copy of a list is:
  li[::-1]

You can also use the builtin "reversed" -- it doesn't return a list,
but rather a reverse iterator. You can create a list from an iterator
by passing it to the list() initializer, like list(reversed(li)).




More information about the Python-list mailing list