Methods on a List

The important thing about list is its items need not have the same type. Many methods can be applied on a list. I’m listing a few out of it here.

List items can be accessed using the index number starting a 0. Using the index we can slice a list to make a new list.

Consider the following list:


  • Slice operations:

a[1:5] gives [2,3,4,5,6]

a[:3] give [1,2,3,4]

a[3:] gives [5,6,7]

a[:] gives [1,2,3,4,5,6,7]

a[-1] gives [7]

  • Concatenation of lists:



a+b gives a new list [1,2,3,4,5,6,7]

  • Nesting of list:



  • Append: append(x) add an item at the end.
  • Extend: extend(L) adds list L to the end of our list.
  • Insert: insert(i,x) inserts x at index i.
  • Remove: remove(x) removes the first occurrence of x.
  • Pop: pop() remove and returns the last element. pop(i) removes and returns element at index i.
  • Index: index(x) returns the index number of first occurance of x.
  • Count: count(x) returns the number of occurrence of x.
  • Sort: sort() sorts the elements of the list.
  • Reverse: reverse() reverses the given list.
  • List as stack: list can be used as stacks. append() does the function of push and pop() does the function of pop.
  • List as queue: list is a little bit difficult to be used as queues, because with popping from the front the entire list has to be moved back one by one. To avoid this problem we can use ‘collections.deque’ on which we can apply popleft() to remove item from the left.
  • List comprehensions: Another interesting use of lists. Lets look it as an example:

>>> a,b=[1,2],[3,4]

>>> [x+y for x in a for y in b]



About Odol Shinu

I've completed my B Tech in Information Technology in 2010 from Government Engineering College Sreekrishnapuram Palakkad under Calicut University.

Posted on August 29, 2010, in Python. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: