Lecture: Methods


Following are some of the functions used formarly in this course:

  • Max()

  • len()

  • round()

  • sorted()

Let's learn a few more:

  • Get index in a list: ?

  • Reversing a list: ?

Note: all the data structures in python are called objects.


Python has built-in methods which informaly are:

Functions that belong to python objects, e.g. A python object of type string has methods, such as:

  • capitalize and

  • replace

Further, objects of type float have "specific methods" depending on the type.


Syntax:

  • object.method_name( <arguments> )
  • The .(dot) is called address off operator which uses reference of specified method to be searched from the standard library of python, which contains list of functions and methods.

To sum things up:

In Python, everything is an object, and each object has a specific method associated with it, depending on the type of object.

Note:

  • Some methods can also, change the objects they are called on.
    • e.g. The .append() method!
  • Consequently, some don't and thus a caution is needed while usig such methods!

Lab: Methods


Objective:

  • Get to know different kinds of methods.
  • Understand the nuances that come packaged with methods.

    • by practising them on data types such as string and list.

  • String Methods -- 100xp, status: Earned
  • List Methods -- 100xp, status: Earned
  • List Methods II -- 100xp, status: Earned

1. String Methods -- 100xp, status: earned


In [3]:
"""
Instructions: 

    + Use the upper() method on room and store the result in room_up.
      Use the dot notation.
      
    + Print out room and room_up. Did both change?
    
    + Print out the number of o's on the variable room by calling count()
      on room and passing the letter "o" as an input to the method.

        - We're talking about the variable room, not the word "room"!
"""
# string to experiment with: room
room = "poolhouse"

# Use upper() on room: room_up
room_up = room.upper()

# Print out room and room_up
print(room)
print( "\n" + room_up )

# Print out the number of o's in room
print("\n" + str( room.count("o") ) )


poolhouse

POOLHOUSE

3

2. List Methods -- 100xp, status: earned

Other Python data types alos have many common method's associated with them, some of these methods are exclusive to some data types.

A few of them we will be experimenting on them:

  • index(), to get the index of the first element of a slist that matches its input.
  • count(), to get the number of times an element appears in a list.


In [25]:
"""
Instructions:

    + Use the index() method to get the index of the element
      in areas that is equal to 20.0. Print out this index.
      
    + Call count() on areas to find out how many times 14.5
      appears in the list. Again, simply print out this number.
    
"""
# first let's look more about these methods
help(str.count)
print(2*"\n===================================================")
help(str.index)
# Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]

# Print out the index of the element 20.0
print( "\nThe index of the element 20.0 is: " + str( areas.index( 20 ) ) )

# Print out how often 14.5 appears in areas
print("\nThe number of times 14.5 occurs is: " + str( areas.count( 14.5 ) ) )


Help on method_descriptor:

count(...)
    S.count(sub[, start[, end]]) -> int
    
    Return the number of non-overlapping occurrences of substring sub in
    string S[start:end].  Optional arguments start and end are
    interpreted as in slice notation.


===================================================
===================================================
Help on method_descriptor:

index(...)
    S.index(sub[, start[, end]]) -> int
    
    Like S.find() but raise ValueError when the substring is not found.


The index of the element 20.0 is: 2

The number of times 14.5 occurs is: 0

3. List Methods II -- 100xp, status: earned


Most list methods will change the list they're called on. E.g.

  • append() : adds and element to the list it is called on.
  • remove(): removes the "1st element" of a list that matches the inuput.
  • reverse() : reverse the order of the elements in the list it is called on.


In [43]:
"""
Instructions: 

    + Use the append method twice to add the size of the
      poolhouse and the garage again:
      
          - 24.5 and 15.45, respectively.
          
          - Add them in order
          
   + Print out the areas.
   
   + Use the reverse() method to reverse the order of the
     elements in areas.
     
   + Print out the area once more.
"""
# Let's look at the help on these methods
help( list.append )
print("=====================================================")
help( list.remove )
print("=====================================================")
help( list.reverse )


Help on method_descriptor:

append(...)
    L.append(object) -> None -- append object to end

=====================================================
Help on method_descriptor:

remove(...)
    L.remove(value) -> None -- remove first occurrence of value.
    Raises ValueError if the value is not present.

=====================================================
Help on method_descriptor:

reverse(...)
    L.reverse() -- reverse *IN PLACE*


In [44]:
# Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]

# Use append twice to add poolhouse and garage size
areas.append( 24.5 )
areas.append( 15.45 )

# Print out areas
print("\nThe new list contains two new items: " + str( areas )  )

# Reverse the orders of the elements in areas
areas.reverse()

# Print out areas
print("\nThe new list has been reversed: " + str( areas ) )


The new list contains two new items: [11.25, 18.0, 20.0, 10.75, 9.5, 24.5, 15.45]

The new list has been reversed: [15.45, 24.5, 9.5, 10.75, 20.0, 18.0, 11.25]