Newbi Q: What is a rational for strings not being lists in Python?

Paul McGuire ptmcg at austin.rr.com
Tue Oct 16 09:15:12 EDT 2007


On Oct 15, 3:03 pm, "Matt McCredie" <mccre... at gmail.com> wrote:
> So, the best way to get the posted
> code to work [...] is to cast the input parameter to a list first.

<snip>

> >>> s = "I am a string"
> >>> x = list(s)
> >>> x
>
> ['I', ' ', 'a', 'm', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g']
>>> "".join(x)
>
> 'I am a string'

Pardon my nit-picking, but the line "x = list(s)" is not casting
anything.  It is constructing a new list from the iterable s.

Even if s is a list, you get back a new list with the same elements:

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
>>> lst = list("ABCDEF")
>>> id(lst)
12249928
>>> id(list(lst))
12250088

(This was a surprise to me too - I thought list(listVar) just returned
back the original listVar.)

-- Paul




More information about the Python-list mailing list