Python list – append or prepend a value

Appending or prepending a value to a list in Python.

Append value

a = ["v1", "v2", "v3", "v4"]
print a
a.append("new val")
print a
['v1', 'v2', 'v3', 'v4']
['v1', 'v2', 'v3', 'v4', 'new val']
Env: Python 2.7.6

Prepend value

a = ["v1", "v2", "v3", "v4"]
print a
a.insert(0, "new val")
print a
a = ["new value2"] + a
print a
['v1', 'v2', 'v3', 'v4']
['new val', 'v1', 'v2', 'v3', 'v4']
['new value2', 'new val', 'v1', 'v2', 'v3', 'v4']
Env: Python 2.7.6
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments