Methods in Python
We earlier learned about various data types in Python such as
str. We also learned about other data structures such as lists. When we create a variable with an integer value, or a list with some elements, what we are actually creating is a python object of that type.
# a is a python object of type integer a = 15 # b is a python object of type string b = "Data Science" # c is a python object of type list c = ["GOOG","MSFT","INTL"]
We also learned about built-in functions in Python. For example, we can use the
max() function to return the maximum value, or the
sum() function to calculate the sum of numbers. Similarly, we also saw that we can create our own custom functions.
Python also has special types of functions which define some characteristic of an object. These are called Methods. Each type of object will have its own set of methods that can be called upon those objects. For example, if you have a string object, you can use the string methods to perform specific tasks on your string object. Two examples are the
capitalize() method and the
replace() method. Similarly, a list object will have its own set of methods available to it, for example
Examples - String Methods
Below are some examples showing the application of string methods.
# course is a string object course = "data science" # The capitalize() method will capitalize the string course.capitalize() # the upper() method will make the string uppercase course.upper() # The replace() method will replace a part of the string with new str.replace(old, new[, max]) # the word "science" will be replaced with "analytics" course.replace("science", "analytics")
Examples - List Methods
# Define a new list prices = [25,67,56,78,89] #The index method gets the index of the element of a list that matches its input #In the following example, the index for the number 56 will be 2. prices.index(56) #The append method adds new elements to the list # After appending the new list will be [25,67,56,78,89,56] prices.append(56) #The count method gets the number of times an element appears in a list #Our list contains the number 56 two times prices.count(56) #The remove() method removes the first element of a list that matches the input #After removing the new list will be [67,56,78,89,56] prices.remove(25) #The reverse() method reverses the order of the elements in the list prices.reverse() #After reversing the list would have been reversed [56,89,78,56,67] print(prices)
- Create a list with the names of your favourite stocks.
- Use the
append()method to add one more stock and print the updatd list
- Use the
index()method to find the index of any stock of your choice.