Python list (array) basics

Python list (or array) – some basic operations.

Initialize list

a = ["1", "2", "3"]
print a
print str(a)
['1', '2', '3']
['1', '2', '3']
Env: Python 2.7.6

access ith item

a = ["v1", "v2", "v3", "v4"]
if len(a) >= 1:
  print a[1]
v2
Env: Python 2.7.6

access last item

a = ["v1", "v2", "v3", "v4"]
if len(a) >= 1:
  print a[-1]
  print a[len(a)-1]
v4
v4
Env: Python 2.7.6

list length/size using len()

Note than len() can also be used to find string size.

a = ["1", "2", "3"]
print len(a)
3
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