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!
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.
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'>
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With