Monday, March 12, 2012

More Methods

In this post, I will show you use of some more methods. By now we should know the general syntax of writing a method which is:

Syntax: object_name.method_name(argument)

So at First Open up the IDLE, and Lets create a List,

>>> wish = ["Hello", "Visitor", "how", "are", "you", "?"]
>>> wish
['Hello', 'Visitor', 'how', 'are', 'you', '?']
>>>

Ok The First Method is "index", which returns the index number of an element in the list.

Lets say we want to know the index number of "are"

Syntax: object-name.index(argument)

>>> wish.index('are')
3
>>>

Next we will see the use another method known as "insert", this method is used to insert an element in a List, at a given index.

Syntax: Object-name.(index_number, "argument")

Lets insert the word "Dear" after "Hello", so the index number of the place where we want to insert is 1.

>>> wish.insert(1, 'Dear')
>>> wish
['Hello', 'Dear', 'Visitor', 'how', 'are', 'you', '?']
>>>

Next Lets see how to remove an element from a list with another method which is "pop". Lets try to remove the word "Visitor"

Syntax: Object-name.pop(argument)

>>> wish.pop(2)
'Visitor'
>>> wish
['Hello', 'Dear', 'how', 'are', 'you', '?']
>>>

Noticed something here?? Unlike other methods, it returns what has been removed, so index number of "Visitor" was 2, so pop takes the argument as index number of the element to be removed.

There is another method of removing an element, known as "remove", this removes/deletes an element but it will not return what has been deleted, like the method 'pop'.

Lets try to remove the word "Dear"

>>> wish.remove('Dear')
>>> wish
['Hello', 'how', 'are', 'you', '?']
>>>

Ok So we have seen the difference between the methods 'pop' and 'remove'.

Lets jump to another Method, which is "reverse", which is Last for the post but not the least.

The method "reverse", as the name suggests reverses a list.

Syntax: object-name.reverse()

>>> wish.reverse()
>>> wish
['?', 'you', 'are', 'how', 'Hello']
>>>

Notice something here, reverse did not take any argument to reverse the string.


Okay, i hope this was informative, and practice this, and don't forget to check on my next post.

Thank You!

3 comments:

  1. Replies
    1. M sorry but things will be confusing, if you don't understand the basic. :) :) Anyways If you point out a part which seems confusing, may b i will try to explain in some other way.

      Delete