Starting up with Python – Part5

I am now on Day2 with my usual articles on “starting up with Python” Its now time to gets on with Methods in Python.  A Method is a Function which is a member of a class. As usual, articles which have been posted already on Python are as follows:

10. Intro to Methods

An action that is assigned to an object. Methods are built-in functions. Let’s see some examples:

So we have numbers = [0, 3, 4, 5]  and we want to append 45 to it using a method

>> numbers
 [0, 3, 4, 5]
 >>> numbers.append(45)
 >>> numbers
 [0, 3, 4, 5, 45]

The count Method will take an object and counts how many times your arguments are in the defined object.

>> name= ['HackersMauritius','HackersWorldwide']
>>> name.count('HackersMauritius')
1
>>> name.count('Hackers')
0

We can also extend a list with the extend function

>> list1 = ['1','2','3','4']
>>> list2 = ['5','6','7','8']
>>> list1
['1', '2', '3', '4']
>>> list2
['5', '6', '7', '8']
>>> list1.extend(list2)
>>> list1
['1', '2', '3', '4', '5', '6', '7', '8']
>>> list2
['5', '6', '7', '8']

11. More Methods

 The method index() returns the lowest index in the list that obj appears. The index method will search for the first occurrence of value and say where it is in the list. We can also insert a parameter in the list.

>> pets=['dog','cat','monkey','crocodile']
>>> pets
['dog', 'cat', 'monkey', 'crocodile']
>>> pets.index('monkey')
2
>>> pets.insert(4, 'bird')
>>> pets
['dog', 'cat', 'monkey', 'crocodile', 'bird']
>>> pets.insert(3, 'alligator')
>>> pets
['dog', 'cat', 'monkey', 'alligator', 'crocodile', 'bird']

We do not have only the insert function but we can also move around too with the same principle that is object.element(parameters)

>> pets
['dog', 'cat', 'monkey', 'alligator', 'crocodile', 'bird']
>>> pets.pop(3)
'alligator'
>>> pets
['dog', 'cat', 'monkey', 'crocodile', 'bird']

Let’s now delete a value from the list.

>> pets
['dog', 'cat', 'monkey', 'crocodile', 'bird']
>>> pets.remove('bird')
>>> pets
['dog', 'cat', 'monkey', 'crocodile']

You will notice that in ‘pop’ it returns a value whereas in remove it simply deletes it from the list.

We can also reverse the words. For example,

>> pets
['dog', 'cat', 'monkey', 'crocodile']
>>> pets.reverse()
>>> pets
['crocodile', 'monkey', 'cat', 'dog']
Nitin J Mutkawoa https://tunnelix.com

Blogger at tunnelix.com | Founding member of cyberstorm.mu | An Aficionado Journey in Opensource & Linux – And now It's a NASDAQ touch!

You May Also Like

More From Author