1# a is a python object of type integer
2a = 15
3# b is a python object of type string
4b = "Data Science"
5# c is a python object of type list
6c = ["GOOG","MSFT","INTL"]
7
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 index()
,count()
and append()
.
Examples - String Methods
Below are some examples showing the application of string methods.
1# course is a string object
2course = "data science"
3# The capitalize() method will capitalize the string
4course.capitalize()
5# the upper() method will make the string uppercase
6course.upper()
7# The replace() method will replace a part of the string with new str.replace(old, new[, max])
8# the word "science" will be replaced with "analytics"
9course.replace("science", "analytics")
10
Examples - List Methods
1# Define a new list
2prices = [25,67,56,78,89]
3#The index method gets the index of the element of a list that matches its input
4#In the following example, the index for the number 56 will be 2.
5prices.index(56)
6#The append method adds new elements to the list
7# After appending the new list will be [25,67,56,78,89,56]
8prices.append(56)
9#The count method gets the number of times an element appears in a list
10#Our list contains the number 56 two times
11prices.count(56)
12#The remove() method removes the first element of a list that matches the input
13#After removing the new list will be [67,56,78,89,56]
14prices.remove(25)
15#The reverse() method reverses the order of the elements in the list
16prices.reverse()
17#After reversing the list would have been reversed [56,89,78,56,67]
18print(prices)
19
Exercise
- 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.