Saturday, 19 March 2016

How to use lists in Python ?


Lists in Python
  • most flexible ordered collection
  • can contain any sort of object : numbers, strings and even other lists
  • define a left to right positional ordering of the items
  • can fetch a component object by indexing the list on the object’s offset : for slicing and concatenation
  • Variable length : List can grow and shrink
  • Heterogeneous : Lists may contain any sort of object

Defining list
>>> aa=[]   # An empty list
>>> aa=[1,2,3,4]   # 4 items, index 0-3

List responds to + and * operations like Strings
>>> aa=[1,2,3]
>>> bb=[4,5,6]
>>> aa+bb

>>> aa*3

Method len() to get size of list and "in" function
>>> aa=[1,2,3]
>>> len(aa)

>>> 3 in aa

append method adds item at end of the list
>>> aa=[]
>>> aa.append(1)
>>> aa.append(2)
>>> aa.append(3)
>>> aa.append(‘4’)
>>> aa.append(5.0)

sort method orders a list (in ascending)
>>> aa=[4,2,6,8,1,3,4,10]
>>> aa.sort()

reverse method reverses the list
>>> aa=[1,2,3,4]
>>> aa.reverse()

pop deletes an item from the end
>>> aa.pop()

No comments:

Post a Comment

Note: only a member of this blog may post a comment.