15

METHODS

by

The Education Machine

[support@theeducationmachine.com]


Till now, we have discussed about various datatypes. Now, its time to deep dive into each datatype's methods.

We know that each variable belongs to specific class based on their values. A class in python consists of various methods or objects.

Methods can be also called as functions. But, what is the difference between methods and functions?

We have used various functions such as print(), type(), id(), etc.

All these functions are universal and can be used independently anywhere in the program. In other words, these functions are not tied to a specific datatype or variables.

Now, to perform any operation directly on variable values, we have to call methods from their respective class. To apply any operation on strings, methods from 'str' class have to be called.

Similarly for integers, methods from 'int' class will be used and respectively for other datatypes as well.

Now, we understand basic difference between Methods and Functions, let us see some additional differences between them:

Functions:

Method:

A method in python is somewhat similar to a function, except it is associated with object/classes. Methods in python are very similar to functions except for two major differences.

  • The method is implicitly used for an object for which it is called.
  • The method is accessible to data that is contained within the class.
  • Unlike a function, methods are called on an object.
  • Unlike method which can alter the object’s state, python function doesn’t do this and normally operates on it.

  • To view all the methods associated to variable's class, just write the variable name with a dot and click tab and you will get the name of methods as shown below:

    reserved_keywords

    Integer Methods

    1.) bit_length

    We learnt bitwise operators from operators section, they work on binary values of numbers.

    bit_length() is used to count the length of binary numbers of an integer.

      num = 10
      num.bit_length()

    Output:
    4

    Let us see the binary value of num.
    Ignore 0b in output's prefix as it is representing it as binary number.

      print(bin(num))

    Output:
    0b1010

    We can also call the method using class of the variable.

      print(int.bit_length(num))

    Output:
    4

    2.) to_bytes(length, byteorder, *, signed=False)

    Return an array of bytes representing an integer.If byteorder is “big”, the most significant byte is at the beginning of the byte array. If byteorder is “little”, the most significant byte is at the end of the byte array. The signed argument determines whether two’s complement is used to represent the integer.

      print((16).to_bytes(3, byteorder = 'big'))

    Output:
    b'\x00\x00\x10'

      print((-16).to_bytes(4, byteorder = 'little', signed= True))

    Output:
    b'\xf0\xff\xff\xff'

    3.) from_bytes(bytes, byteorder, *, signed=False)

    Returns the integer represented by the given array of bytes.

      print(int.from_bytes(b'', byteorder ='little'))

    Output:
    16

    Similarly check & practice methods for float and complex class.

      float.

      complex.


    String Methods

    1.) capitalize

    It capitalizes first letter of string.

      name = 'pyTHOn'
      name.capitalize()

    Output:
    'Python'

    2.) lower

    The lower() method returns a string where all characters are lower case.

  • Symbols are ignored.
  •   name.lower()

    Output:
    'python'

    3.) casefold

    The casefold() method returns a string where all the characters are lower case.

    This method is similar to the lower() method, but the casefold() method is stronger, more aggressive, meaning that it will convert more characters into lower case, and will find more matches when comparing two strings and both are converted using the casefold() method.

      name = 'pyTHOn'
      name.casefold()

    Output:
    'python'

    ß is equivalent to ss in German.
    Casefold() can convert german character to english character while lower cannot. Thus, casefold is aggressive and more stronger.

      firstString = "der Fluß"
      secondString = "der Fluss"

      print(firstString.casefold())
      if firstString.casefold() == secondString.casefold():
          print('The strings are equal.')
      else:
          print('The strings are not equal.')

    Output:
    der fluss
    The strings are equal.

    Using lower().
    We can see that lower() is unable to convert the german character.

      print(firstString.lower())
      if firstString.lower() == secondString.lower():
          print('The strings are equal.')
      else:
          print('The strings are not equal.')

    Output:
    der fluß
    The strings are not equal.

    4.) upper

    The upper() method returns a string where all characters are upper case.

    The upper() methods returns the uppercased string from the given string. It converts all lowercase characters to uppercase.If no lowercase characters exist, it returns the original string.

      name = 'pYthon'
      name.upper()

    Output:
    'PYTHON'

      firstString = "der Fluß"
      firstString.upper()

    Output:
    'DER FLUSS'

    5.) Split

    split() method returns a list of strings after breaking the given string by the specified separator.

      string = "This is python session"
      print(string.split(' '))
      l = string.split()
      print(l)

    Output:
    ['This', 'is', 'python', 'session']
    ['This', 'is', 'python', 'session']

      name = input("Enter your name,gender").split(',')
      print(name)

    Output:
    Enter your name,genderabc,F
    ['abc', 'F']


    Tuple Methods

    1.) count

    The count() method returns the number of times the specified element appears in the tuple.

      t = ('This', 'is', 'python', 'session!', 'python', 'iss', 'awesome')
      t.count('python')

    Output:
    2

      t.count('is')

    Output:
    1

    2.) index

    index() method searches for the given element in a tuple and returns its position. It returns first occurrence of the element in the tuple. Index starts from 0 and end at n-1 where n is length of tuple.

      t = ('This', 'is', 'python', 'session!', 'python', 'iss', 'awesome')
      t.index('python')

    Output:
    2

      t.index('python', 3)

    Output:
    4


    List Methods

    1.) append

    The append() method adds an item to the end of the list.

      l = ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome']
      l.append('python')
      print(l)

    Output:
    ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome', 'python']

    2.) clear

    The clear() method removes all items from the list.

      l.clear()
      print(l)

    Output:
    []

    Other methods to clear a list:

      l = ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome']
      print(l)
      l = []
      print(l)

    Output:
    ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome']
    []

      l = ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome']
      print(l)
      l *= 0
      print(l)

    Output:
    ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome']
    []

      l = ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome']
      print(l)
      del l[:]
      print(l)

    Output:
    ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome']
    []

    3.) copy

    copy() method returns a shallow copy of a list.

    Shallow copy means the any modification in new list won’t be reflected to original list.

      m = l.copy()

      l = ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome']
      
      m = l.copy()
      print(m)
      print(l)

    Output:
    ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome']
    ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome']

      l.append('python')
      
      print(m)
      print(l)

    Output:
    ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome']
    ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome', 'python']

      m.append('python')
      
      print(m)
      print(l)

    Output:
    ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome', 'python']
    ['This', 'is', 'python', 'session!', 'python', 'iss', 'awesome', 'python']


    Set Methods

    1.) add

    add() method adds a given element to a set if the element is not present in the set.

      s = {'This', 'is', 'python', 'session!', 'python', 'iss', 'awesome'}
      s.add('python is really awesome')
      print(s)

    Output:
    {'This', 'python', 'iss', 'is', 'python is really awesome', 'awesome', 'session!'}

    2.) clear

    The clear() method removes all elements from the set.

      s.clear()
      print(s)

    Output:
    set()

    3.) intersection

    intersection() method returns a new set with elements that are common to all sets.

      s = {'This', 'is', 'python', 'session!', 'python', 'iss', 'awesome'}
      s1 = {'python', 'awesome'}
      s.intersection(s1)

    Output:
    {'awesome', 'python'}

      s = new = s.intersection(s1)
      print(new)

    Output:
    {'python', 'awesome'}


    Dictionary Methods

      d = {'name': 'testuser', 'age': 20}
      print(d, type(d))

    Output:
    {'name': 'testuser', 'age': 20} <class 'dict'>

    1.) items

    Return the dictionary's key-value pairs.

      d = {'name': 'testuser', 'age': 20}
      print(d, type(d))
      d.items()

    Output:
    {'name': 'testuser', 'age': 20} <class 'dict'>

    dict_items([('name', 'testuser'), ('age', 20)])

    2.) keys

    Return the dictionary's keys.

      d.keys()

    Output:
    dict_keys(['name', 'age'])

    Iterate over dictionary keys.

      for i in d.keys():
          print(i)

    Output:
    name
    age

    3.) values

    Return the dictionary's values.

      d.values()

    Output:
    dict_values(['testuser', 20])

    Iterate over dictionary values.

      for i in d.values():
          print(i)

    Output:
    testuser
    20