Python: initialize a list

I met this issue last week, and finally got a proper way to handle it.

We normally init a list like this “list=[]“, then how can we initialize a python list with a string variable?

Here’s my example. We created a list “a” and its initial value is [“abc”]:

Macbook-pro:~ joseph$ python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> try:
...  a.append("abc")
... except NameError:
...  a="abc".split()
...
>>> a
['abc']
>>> try:
...  a.append("abc")
... except NameError:
...  a="abc".split()
...
>>> a
['abc', 'abc']

Python is so wonderful, and I’m just a python beginner..

2 thoughts on “Python: initialize a list

Leave a comment

Your email address will not be published. Required fields are marked *