Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does list(string) split the string to an array of characters in python?

Tags:

python

a = "Stack"
aList = list(a)

This gives me an array like this ['S','t',a','c','k']

I want to know how this list(string) function works!

like image 492
Jagadheshwar Avatar asked Feb 26 '12 02:02

Jagadheshwar


2 Answers

A string is an iterable type. For example, if you do this:

for c in 'string':
    print c

You get

s
t
r
i
n
g

So passing a string to list just iterates over the characters in the string, and places each one in the list.

like image 55
senderle Avatar answered Oct 28 '22 18:10

senderle


String is iterable in python because you can do

>>> for ch in "abc":
...         print ch
...
a
b
c
>>>

and if you take a look at list class construtor using help("list") in your python interpreter

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items

So, list("hello") returns a new list initialized.

>>> x = list("hello")
>>> type(x)
<type 'list'>
>>>
like image 40
RanRag Avatar answered Oct 28 '22 18:10

RanRag