Python Methods

Updated: Aug 23, 2020



Python Methods


Method is a function that “belongs to” an object. (In Python, the term method is not unique to class instances: other object types can have methods as well. For example, list objects have methods called append, insert, remove, sort, and so on.


Methods are in the form:


object.method(arg1,arg2,etc...)

Let's take a quick look at what an example of the various methods a list has:


# Create a simple list 
lst = [1,2,3,4,5]

append() allows us to add elements to the end of a list:


Example:


lst.append(6)
print(lst)

Output:



[1,2,3,4,5,6]



Great!

The count() method will count the number of occurrences of an element in a list.


Example:


# Check how many times 2 shows up in the list 
print(lst.count(2))

Output:


1


insert(): Inserts an elements at specified position in a list


Note: Position mentioned should be within the range of List, as in this case between 0 and 4, otherwise would throw IndexError.

Example:



lst=['Mathematics', 'chemistry', 1997, 2000, 20544]
# Insert at index 2 value 10087 
lst.insert(2,10087)
print(lst) 


Output:



['Mathematics', 'chemistry', 10087, 1997, 2000, 20544]



extend(): Adds contents to list2 to the end of list1.


Example:



list1 = [1, 2, 3] 
list2 = [2, 3, 4, 5] 
  
# Add List2 to List1 
list1.extend(list2)         
print(list1)


Output:



[1, 2, 3, 2, 3, 4, 5]



pop(): Index is not a necessary parameter, if not mentioned takes the last index.


Example:



list = [2.3, 4.445, 3, 5.33, 1.054, 2.5] 
print(list.pop()) 

Output:



2.5


Example:



list = [2.3, 4.445, 3, 5.33, 1.054, 2.5] 
print(list.pop(0))

Output:



2.3



remove(): Element to be deleted is mentioned using list name and element.


Example:



list = [2.3, 4.445, 3, 5.33, 1.054, 2.5] 
list.remove(3) 
print(list)


Output:



[2.3, 4.445, 5.33, 1.054, 2.5]



reverse() is an inbuilt method in Python programming language that reverses objects of list in place.


Example:



list1 = [1, 2, 3, 4, 1, 2, 6]  
list1.reverse()  
print(list1) 
 

Output:



[6, 2, 1, 4, 3, 2, 1]



sort() method sorts the list ascending by default.


Example:



cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars)

Output:


['BMW', 'Ford', 'Volvo']



That's it about methods, in the next article we will discuss about functions.



14 views0 comments
 

Subscribe Form

©2020 by Linux Advise