# 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:

*a=[1,2,3,4,5,6,7]*

- 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=[1,2,3,4]*

*b=[5,6,7]*

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

- Nesting of list:

*p=[1,2]*

*q=[3,p,4]*

- 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]*

*[4,5,6,7]
*

Advertisements

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

## Leave a comment

## Comments 0