Uncategorized

Method Overloading in Python

In this article, let us look at Method Overloading in Python.

Method Overloading:

Method Overloading is a form of Compile time polymorphism. In the case of method overloading, multiple methods belonging to the same class can have the same method name but different number of signatures/ arguments.

Method overloading can be used to add more to the behavior of the concerned methods. A user will not require more than one class to implement it.

NOTE:

Note that Python does not support method overloading. A user may overload 
all of the methods, but they will only be able to use the
lastest defined method.

Example

Approach:

  • Create a class say MethodOverloading
  • Inside the class, create a function say multiply which accepts two numbers as arguments and prints the multiplication result of those two numbers.
  • Create another function with the same name say multiply which accepts three numbers as arguments and prints the multiplication result of those three numbers.
  • Create an object for the above MethodOverloading() class.
  • Pass two numbers as arguments to the multiply() function and apply it on the above object and print the result.
  • Pass three numbers as arguments to the multiply() function and apply it on the above object and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a class say MethodOverloading
class MethodOverloading:
   # Create a function say multiply which accepts two numbers as arguments 
   # and prints the multiplication result of those two numbers
   def multiply(self, x, y):
       print(x*y)
   # Create another function with the same name say multiply which accepts three 
   # numbers as arguments and prints the multiplication result of those three numbers
   def multiply(self, x, y, z):
       print(x*y*z)

# Create an object for the above MethodOverloading() class      
obj =MethodOverloading()
# Pass two numbers as arguments to the multiply() function and apply it 
# on the above object and print the result
print(obj.multiply(2, 3))
# Pass three numbers as arguments to the multiply() function and apply it 
# on the above object and print the result
print(obj.multiply(2, 3, 4))

Output:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-7d5007590dae> in <module>
14 # Pass two numbers as arguments to the multiply() function and apply it
15 # on the above object and print the result
---> 16 print(obj.multiply(2, 3))
17 # Pass three numbers as arguments to the multiply() function and apply it
18 # on the above object and print the result

TypeError: multiply() missing 1 required positional argument: 'z'

Explanation:

Python does not support method overloading because Python always uses the last defined method. We can still overload methods in Python, but it’s pointless. However, method overloading can be implemented in Java, C++, and other languages in the manner described above.

Another way to perform method overloading in Python is as follows:

Approach:

  • Create a class say MethodOverloading.
  • Create a function say multiply which accepts two numbers as arguments and prints the multiplication result of those two numbers based on conditions.
  • Check if both the numbers are not equal to None using the if conditional statement, and operator.
  • If it is true then return the multiplication of both the numbers.
  • Else if Check only the first number passed is not None using the elif conditional statement.
  • If it is true then return only the first number.
  • Else return 0.
  • Create an object for the above MethodOverloading() class.
  • Call the above multiply() function without passing any arguments and print the result.
  • Call the above multiply() function by passing only one number as an argument and print the result.
  • Call the above multiply() function by passing two numbers as arguments and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a class say MethodOverloading
class MethodOverloading:
    # Create a function say multiply which accepts two numbers as arguments 
    # and prints the multiplication result of those two numbers based on conditions
    def multiply(self, a = None, b = None):
        # Check if both the numbers are not equal to None using the if conditional 
        # statement, and operator
        if a!= None and b!= None:
            # If it is true then return the multiplication of both the numbers
            return  a*b
        # else if Check only the first number passed is not None using the elif conditional statement
        elif a!= None:
            # If it is true then return only the first number
            return a
        else:
            # Else return 0
            return 0

# Create an object for the above MethodOverloading() class  
class_object = MethodOverloading()

# Call the above multiply() function without passing any arguments and print the result
print("Result = ", class_object.multiply())
# Call the above multiply() function by passing only one number as an argument and print the result
print("Result = ", class_object.multiply(3))
# Call the above multiply() function by passing two numbers as arguments and print the result
print("Result = ", class_object.multiply(4, 5))

Output:

Result = 0
Result = 3
Result = 20

Advantages of Method overloading

  • Reduces complexities and improves code quality
  • Method overloading is also used for reusability and easy accessibility.
  • Using Python method overloading, you can make multiple methods appear logically as a single method. For example, we have only one method – get area – that can be used to calculate the area of different shapes depending on the type of input given to the function while still presenting itself logically as one method. This improves the readability of the code, making it easier for the programmer to write code and increasing the programmer’s efficiency.
  • We can also keep backward compatibility by using method overloading. What does this imply? If we have a method that performs complex calculations, we could add a new requirement to it that allows it to perform the same complex calculation with minor changes. If we add a new parameter (optional parameter), its presence will be used to perform calculations in either the old or new way.

Method overloading In Brief

  • Same method name but different number of arguments.
  • Inheritance is not required(optional).
  • It is an example of compile time polymorphism.
  • It is performed between methods within the class.
  • Overloading can be done within a class
  • Method Overloading is used to add more to the behavior of methods.
  • Static methods can be overloaded here.
  • It is related with Polymorphism concept of OOPs.

Method overloading allows you to call the same method in multiple ways. All of the methods will have the same name, but there may be three differences:

  • The number of parameters could vary.
  • The data type of arguments
  • The order of the parameters

Difference between Method Overloading and Method Overriding in Python

In this article, let us look at Method Overloading and Method Overriding in python and what are the differences between Method Overloading and Method Overriding.

Method Overloading:

Method Overloading is a form of Compile time polymorphism. In the case of method overloading, multiple methods belonging to the same class can have the same method name but different signatures.

Method overloading can be used to add more to the behavior of the concerned methods. A user will not require more than one class to implement it.

NOTE:

Note that Python does not support method overloading. A user may overload 
all of the methods, but they will only be able to use the
lastest defined method.

Example

Approach:

  • Create a class say MethodOverloading
  • Create a function say multiply which accepts two numbers as arguments and prints the multiplication result of those two numbers.
  • Create another function with the same name say multiply which accepts three numbers as arguments and prints the multiplication result of those three numbers.
  • Create an object for the above MethodOverloading() class
  • Pass two numbers as arguments to the multiply() function and apply it on the above object and print the result.
  • Pass three numbers as arguments to the multiply() function and apply it on the above object and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a class say MethodOverloading
class MethodOverloading:
   # Create a function say multiply which accepts two numbers as arguments 
   # and prints the multiplication result of those two numbers
   def multiply(self, x, y):
       print(x*y)
   # Create another function with the same name say multiply which accepts three 
   # numbers as arguments and prints the multiplication result of those three numbers
   def multiply(self, x, y, z):
       print(x*y*z)

# Create an object for the above MethodOverloading() class      
obj =MethodOverloading()
# Pass two numbers as arguments to the multiply() function and apply it 
# on the above object and print the result
print(obj.multiply(2, 3))
# Pass three numbers as arguments to the multiply() function and apply it 
# on the above object and print the result
print(obj.multiply(2, 3, 4))

Output:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-7d5007590dae> in <module>
14 # Pass two numbers as arguments to the multiply() function and apply it
15 # on the above object and print the result
---> 16 print(obj.multiply(2, 3))
17 # Pass three numbers as arguments to the multiply() function and apply it
18 # on the above object and print the result

TypeError: multiply() missing 1 required positional argument: 'z'

Explanation:

Python does not support method overloading because Python always uses the last defined method. We can still overload methods in Python, but it’s pointless. However, method overloading can be implemented in Java, C++, and other languages in the manner described above.

Another way to perform method overloading in Python is as follows:

# Create a class say MethodOverloading
class MethodOverloading:
    # Create a function say multiply which accepts two numbers as arguments 
    # and prints the multiplication result of those two numbers based on conditions
    def multiply(self, a = None, b = None):
        # Check if both the numbers are not equal to None using the if conditional 
        # statement, and operator
        if a!= None and b!= None:
            # If it is true then return the multiplication of both the numbers
            return  a*b
        # else if Check only the first number passed is not None using the elif conditional statement
        elif a!= None:
            # If it is true then return only the first number
            return a
        else:
            # Else return 0
            return 0

# Create an object for the above MethodOverloading() class  
class_object = MethodOverloading()

# Call the above multiply() function without passing any arguments and print the result
print("Result = ", class_object.multiply())
# Call the above multiply() function by passing only one number as an argument and print the result
print("Result = ", class_object.multiply(3))
# Call the above multiply() function by passing two numbers as arguments and print the result
print("Result = ", class_object.multiply(4, 5))

Output:

Result = 0
Result = 3
Result = 20

Method Overriding

Method overriding is a form of Run time polymorphism. The child class provides the specific implementation of the method that is already provided by the parent class. It is used to change the behavior of existing methods, and method overriding requires at least two classes. In method overriding, inheritance is always required because it occurs between methods from the parent class (superclass) and the child class (child class).

Approach:

  • Create a parent class say FirstClass
  • Inside the parent class, create a function say display1().
  • Create another function say display2.
  • Create a child class say SecondClass() which inherits properties from the parent class, FirstClass().
  • Create a function with the same name say display1 as in the parent which modifies or overrides the text when it is called.
  • Create an object for the child class say SecondClass() and store it in a variable.
  • Call the display1() function of the SecondClass() which overrides the display1() function of the FirstClass.
  • The Exit of the Program.

Below is the implementation:

# Create a parent class say FirstClass
class FirstClass:
    
    # Create a function say display1
    def display1(self):
        print('display_1 of the FirstClass')
    
    # Create another function say display2
    def display2(self):
        print('display_2 of the FirstClass')
    
# Create a child class say SecondClass which inherits properties from parent class, FirstClass
class SecondClass(FirstClass):
    
    # Create a function with the same name say display1 as in the parent parent
    # which modifies or overrides the text when it is called
    def display1(self):
        print('Overriding display1() class of FirstClass by the SecondClass')
        
    def display3(self):
        print('display_3 of the SecondClass')
        

# Create an object for the child class say SecondClass() and store it in a variable
secondClass_object = SecondClass()
    
# Call the display1() fuction of the SecondClass() which overrides the 
# display1() function of the FirstClass
secondClass_object.display1()

Output:

Overriding display1() class of FirstClass by the SecondClass

Difference between Method Overloading and Method Overriding in Python

            Method Overloading               Method Overriding
Same method name but the different number of arguments Same method name and the same number of arguments
Inheritance is not required(optional). Inheritance is not required(optional).
It is an example of compile time polymorphism. It is an example of run-time polymorphism.
It is performed between methods within the class. Method overriding occurs between parent and child class methods.
Overloading can be done within a class A minimum of two classes are required for overriding  
Overloading is used to add more to the behavior of methods. Overriding is used to change the behavior of existing methods.
Static methods can be overloaded here Static methods cannot be overloaded here
It is related with Polymorphism It is related with Inheritance.

Return Statement in Python Function

To return a value from a function, use the Python return statement. In a function, the user can only utilize the return statement. It can only be used within the Python function. A return statement contains the return keyword as well as the value to be returned after that.
We can return a single value or multiple values using the return statement in the python function.

Returning Single Value using return Statement in Python Function

Approach:

  • Create a function say multiply() which accepts two numbers as an argument
  • Inside the function, multiply the above passed two numbers and store it in a variable
  • Return the above multiplication result using the return statement
  • Call the above-created multiply() function by passing some random two numbers as arguments
    and store it in another variable
  • Here it multiplies the two numbers(3*4) that we pass by calling the function and stores the result
  • Print the multiplication of the given two numbers.
  • The Exit of the Program.

Below is the implementation:

# Create a function say multiply() which accepts two numbers as an argument
def multiply(x, y):
  # Inside the function, multiply the above passed two numbers and
  # store it in a variable
  mul = x * y
  # Return the above multiplication result using the return statement
  return mul

# Call the above created multiply() function by passing some random two numbers as arguments
# and store it in another variable
# Here it multiplies the two numbers(3*4) that we pass by calling the function and stores the result
rslt = multiply(3, 4)
# Print the multiplication of given two numbers
print(rslt)

Output:

12

Returning Multiple Values using return Statement in Python Function

Approach:

  • Create a function say multiply() which accepts two numbers as an argument
  • Inside the function, multiply the above passed two numbers and store it in a variable
  • Calculate the average of the given two numbers and store it in another variable
  • Return the above multiplication, and average results using the return statement
  • Here we can observe that we are returning multiple values
  • Call the above-created multiply() function by passing some random two numbers as arguments
    and store it in another variable
  • Here it stores both multiplication and average results of the given two numbers
  • Print the multiplication and average of given two numbers.
  • The Exit of the Program.

Below is the implementation:

# Create a function say multiply() which accepts two numbers as an argument
def multiply(x, y):
  # Inside the function, multiply the above passed two numbers and
  # store it in a variable
  mul = x * y
  # Calculate the average of given two numbers and store it in another variable
  average = (x+y)/2
  # Return the above multiplication, average results using the return statement
  # Here we can observe that we are returning multiple values
  return mul, average

# Call the above created multiply() function by passing some random two numbers as arguments
# and store it in another variable
# Here it stores both multiplication, average results of the given two numbers
rslt = multiply(3, 4)
# Print the multiplication, average of given two numbers
print("The multiplication, average of given two numbers is:")
print(rslt)

Output:

The multiplication, average of given two numbers is:
(12, 3.5)

NOTE:

Not only two values, but you can also return multiple values 
using the return statement in python function

Indexing in Python with Examples

What exactly is indexing in Python? – As simple as it appears, explaining how indexing works in Python can be a little tricky. So take a seat and read this article to gain a better understanding of indexing in Python.

Iterables:

Before we get started with indexing, let’s define iterables and their primary function. Iterable knowledge is essential for getting behind indexing.

So, what exactly are iterables?

In Python, it is a special type of object that may be iterated over. That is, you can traverse through all of the various elements or entities present within the object or entity. It is simple to accomplish using for loops.

All iterable items have two special methods called __iter__() or __getitem__() that implement Sequence Semantics.

Lists, tuples, strings etc are examples of iterables in python.

Example

1)For Lists

Approach:

  • Give the list as static input and store it in a variable.
  • The list is iterable.
  • Iterate in the above list using the for loop.
  • Inside the for loop, print the elements of the given list by printing the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
# List is an iterable
gvn_lst = [1, 2, 3, 4, 5]
# Iterate in the above list using the for loop.
for elemnt in gvn_lst:
    # Inside the for loop, print the element of the given list by printing the
    # iterator value.
    print(elemnt)

Output:

1
2
3
4
5

2)For Strings

Example

Approach:

  • Give the string as static input and store it in a variable.
  • Strings are also examples of an iterable.
  • Iterate in the above string using the for loop.
  • Inside the for loop, print the characters of the given string by printing the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
# Strings are also examples of an iterable.
gvn_str = "Python-programs"
# Iterate in the above string using the for loop.
for chrctr in gvn_str:
    # Inside the for loop, print the characters of the given string by printing the
    # iterator value.
    print(chrctr)

Output:

P
y
t
h
o
n
-
p
r
o
g
r
a
m
s

Now that we know what Iterables are in Python. How does this relate to indexing?

Indexing in Python

Indexing in Python is a method of referring the individual items within an iterable based on their position.

In other words, you can directly access the desired elements within an iterable and perform various operations based on your requirements.

Note: 

Objects in Python are “zero-indexed,” which means the position count starts at zero. A similar pattern is followed by several other programming languages. For example C, C++, java, etc,
So, let’s say there are 6 elements in a list. The first element (i.e. the leftmost element) then takes the “zeroth” position, followed by the elements in the first, second, third, fourth, and fifth positions.

Let  array =     10  11  12  13  14

indexes :          0    1    2   3    4

Example

Approach:

  • Give the list as static input and store it in a variable.
  • Apply index() function to the given list by passing “Python” as an argument to it to get index(position) of “Python”.
  • Store it in another variable.
  • Print the index of “Python”.
  • Similarly, print the index of “welcome”.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ["welcome", "to", "Python", "programs"]
# Apply index() function to the given list by passing "Python" as an argument
# to it to get index(position) of "Python"
# Store it in a variable.
indx = gvn_lst.index("Python")
# Print the index of "Python".
print("The Index of Python = ", indx)
# Similarly, print the index of "welcome".
print("The Index of welcome = ", gvn_lst.index("welcome"))

Output:

The Index of Python =  2
The Index of welcome =  0

When the index() method on a list is invoked with the item name as an argument, the index of a specific item within the list is displayed.

Now, we will see how to use the index() method on iterable objects.

Index Operator in Python

The Python Index Operator is represented by opening and closing square brackets [ ].

Syntax:

objectname[n]

n – It is an Integer. It is representing the position of the element we want to access.

Example

Approach:

  • Give the string as static input and store it in a variable.
  • Pass some random number to the given string to get the element present at the given index number.
  • Store it in another variable.
  • Print the element present at the 4th index.
  • Similarly, try for the other numbers.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "Python-programs"
# Pass some random number to the given string to get the element present
# at the given index number.
# Store it in another variable.
elemnt = gvn_str[4]
# Print the element present at the 4th index.
print(elemnt)
# Similarly, try for the other numbers.
print(gvn_str[6])
print(gvn_str[2])
print(gvn_str[8])

Output:

o
-
t
r

Negative Indexing

We just learnt how to use indexing in Lists and Strings to find specific objects of interest. Although we’ve used a positive integer inside our index operator (the square brackets) in all of our prior examples, this isn’t always necessary.

Negative integers are useful when we want to find the last few items of a list or when we want to index the list from the opposite end. Negative Indexing refers to the process of indexing from the opposite end.

Note: It should be noted that with negative indexing, the last element is represented by -1 rather than -0.

# Give the list as static input and store it in a variable.
gvn_lst = ["welcome", "to", "Python", "programs"]
# Using negative indexing to print the last item in a given list
print(gvn_lst[-1])
# Printing the first item in a given list
print(gvn_lst[-4])
# Printing the last second item in a given list
print(gvn_lst[-3])

Output:

programs
welcome
to

Python Itertools.chain() Function with Examples

Itertools Module:

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings. Chain is one such itertools function ().

Itertools.chain() Function:

It’s a function that takes a list of iterables and returns a single iterable. It combines all of the iterables and returns a single iterable as output. Its output cannot be directly used and must thus be explicitly converted into iterables. This function belongs to the iterators terminating iterators category.

Syntax:

chain (*iterables)

Examples:

Example1:

Input:

Given first List = [9, 8, 7, 6]
Given second List = [40, 30, 20, 10]

Output:

The result after chaining the given two lists:
[9, 8, 7, 6, 40, 30, 20, 10]

Explanation:

Here the chain() function combines the given first and second list and
returns a new list[9, 8, 7, 6, 40, 30, 20, 10]

Example2:

Input:

Given first string = "hello"
Given second string = "ALL"

Output:

The result after chaining the given two strings:
['h', 'e', 'l', 'l', 'o', 'A', 'L', 'L']

Itertools.chain() Function with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Import itertools module using the import keyword.
  • Give the first list as static input and store it in a variable.
  • Give the second list as static input and store it in another variable.
  • Pass the given first and second lists as the arguments to the itertools.chain() method that combines(chains) the given two lists.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in a variable.
  • Print the result after chaining the given two lists.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the first list as static input and store it in a variable.
fst_lst = [9, 8, 7, 6]
# Give the second list as static input and store it in another variable.
scnd_lst = [40, 30, 20, 10]
# Pass the given first and second lists as the arguments to the itertools.chain()
# method that combines(chains) the given two lists.
# Store it in another variable.
rslt_chain = itertools.chain(fst_lst, scnd_lst)
# Convert the above result into a list using the list() function and store it
# in a variable.
rslt_lst = list(rslt_chain)
# Print the result after chaining the given two lists.
print("The result after chaining the given two lists:")
print(rslt_lst)

Output:

The result after chaining the given two lists:
[9, 8, 7, 6, 40, 30, 20, 10]

For Strings

Approach:

  • Import itertools module using the import keyword.
  • Give the first string as static input and store it in a variable.
  • Give the second string as static input and store it in another variable.
  • Pass the given first and second strings as the arguments to the itertools.chain() method that combines(chains) the given two strings.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in a variable.
  • Print the result after chaining the given two strings.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the first string as static input and store it in a variable.
fst_str = "hello"
# Give the second string as static input and store it in another variable.
scnd_str = "ALL"
# Pass the given first and second strings as the arguments to the itertools.chain()
# method that combines(chains) the given two strings.
# Store it in another variable.
rslt_chain = itertools.chain(fst_str, scnd_str)
# Convert the above result into a list using the list() function and store it
# in a variable.
rslt_lst = list(rslt_chain)
# Print the result after chaining the given two strings.
print("The result after chaining the given two strings:")
print(rslt_lst)

Output:

The result after chaining the given two strings:
['h', 'e', 'l', 'l', 'o', 'A', 'L', 'L']

Method #2: Using Built-in Functions (User Input)

Approach:

  • Import itertools module using the import keyword.
  • Give the first list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the second list as user input using list(),map(),input(),and split() functions.
  • Store it in another variable.
  • Pass the given first and second lists as the arguments to the itertools.chain() method that combines(chains) the given two lists.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in a variable.
  • Print the result after chaining the given two lists.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the first list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
fst_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Give the second list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
scnd_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
   
# Pass the given first and second lists as the arguments to the itertools.chain()
# method that combines(chains) the given two lists.
# Store it in another variable.
rslt_chain = itertools.chain(fst_lst, scnd_lst)
# Convert the above result into a list using the list() function and store it
# in a variable.
rslt_lst = list(rslt_chain)
# Print the result after chaining the given two lists.
print("The result after chaining the given two lists:")
print(rslt_lst)

Output:

Enter some random List Elements separated by spaces = 10 15 20
Enter some random List Elements separated by spaces = 100 200 300
The result after chaining the given two lists:
[10, 15, 20, 100, 200, 300]

For Strings

Approach:

  • Import itertools module using the import keyword.
  • Give the first string as user input using the input() function and store it in a variable.
  • Give the second string as user input using the input() function and store it in another variable.
  • Pass the given first and second strings as the arguments to the itertools.chain() method that combines(chains) the given two strings.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in a variable.
  • Print the result after chaining the given two strings.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the first string as user input using the input() function and store it in a variable.
fst_str = input("Enter some random string = ")
# Give the second string as user input using the input() function and 
# store it in another variable.
scnd_str = input("Enter some random string = ")
# Pass the given first and second strings as the arguments to the itertools.chain()
# method that combines(chains) the given two strings.
# Store it in another variable.
rslt_chain = itertools.chain(fst_str, scnd_str)
# Convert the above result into a list using the list() function and store it
# in a variable.
rslt_lst = list(rslt_chain)
# Print the result after chaining the given two strings.
print("The result after chaining the given two strings:")
print(rslt_lst)

Output:

Enter some random string = good
Enter some random string = morning
The result after chaining the given two strings:
['g', 'o', 'o', 'd', 'm', 'o', 'r', 'n', 'i', 'n', 'g']

Python – Keywords and Identifiers

In this article we are going to discuss about keywords and identifiers in Python.

Keywords are prearranged and predefined words in python. Every keywords are written in lower case except True and False. If we count there are 33 keywords in python. Keywords are case sensitive. We can not create any function or identifiers with matching keyword name. I python these keywords are  made for particular purpose.

All Python Keywords are listed below:

1 and It is a logical operator. If both the operands are true it returns true otherwise false.
2 Or It is also a logical operator. Returns true if anyone operand is true otherwise return false.
3 not This is again a logical operator. Returns True if the operand is false else return false.
4 if  Conditional statement.
5 elif Elif is a condition statement used with if statement the elif statement is executed if the previous conditions were not true
6 else Else is used with if and elif conditional statement the else block is executed if the given condition is not true.
7 for This is created for a loop.
8 while This keyword is used to create a while loop.
9 break This is used to terminate the loop.
10 as This is used to create an alternative.
11 def It helps us to define functions.
12 lambda It used to define the anonymous function.
13 pass This is a null statement that means it will do nothing.
14 return It will return a value and exit the function.
15 True This is a Boolean value.
16 False This is also a Boolean value.
17 try It makes a try-except statement.
18 with The with keyword is used to simplify exception handling.
19 assert This function is used for debugging purposes. Usually used to check the correctness of code
20 class It helps us to define a class.
21 continue It continues to the next iteration of a loop
22 del It deletes a reference to an object.
23 except Used with exceptions, what to do when an exception occurs
24 finally Finally is use with exceptions, a block of code that will be executed no matter if there is an exception or not.
25 from The form is used to import specific parts of any module.
26 global This declares a global variable.
27 import This is used to import a module.
28 in It’s used to check if a value is present in a list, tuple, etc, or not.
29 is This is used to check if the two variables are equal or not.
30 None This is a special constant used to denote a null value or avoid. It’s important to remember, 0, any empty container(e.g empty list) do not compute to None
31 nonlocal It’s declared a non-local variable.
32 raise This raises an exception
33 yield It’s ends a function and returns a generator.

Python Identifiers

Python identifiers are generally used to recognize a variable, function, class etc. There are some rules which we should follow while choosing a name for identifier-

1.Identifier should start with a character or Underscore after that use digit.

2.Characters are A-Z or a-z, an Underscore ( _ ) , and digit (0-9).

  • For example, value_count, dataLoader etc. are some valid identifier names.

3.We should not use special characters ( #, @, $, %, ! ) in identifiers.

4.No limitation on the length of the identifier.

5.Identifiers are case sensitive, i.e., ‘define’ & ‘Define’ are two different identifiers in Python.

6.Avoid using two underscore while giving identifiers name  like __len__ or _load__

Conclusion:

In this article we have discussed all about keywords and identifiers in Python in details. Thank You!

 

Delete elements from a Numpy Array by value or conditions in Python

Deleting elements from a NumPy Array by value or conditions in Python.

In this article we will discuss about how to delete elements from a NumPy Array by based on matching values or multiple conditions.

Remove all occurrences of an element with given value from numpy array :

Suppose we have a NumPy array and we want to delete all the occurrences of that particular element from that Numpy array.

#Program :

import numpy as np
# numpy array created from a list
arr = np.array([40,50,60,70,80,90,40,10,20,40])
print('Numpy Array before deleting all occurrences of 40 :')
print(arr)

# Removing all occurrences of elements with value 40 from numpy array
arr = arr[arr != 40]
print('Modified Numpy Array after deleting all occurrences of 40 :')
print(arr)
Output :
Numpy Array before deleting all occurrences of 40 :
[40 50 60 70 80 90 40 10 20 40]
Modified Numpy Array after deleting all occurrences of 40 :
[50 60 70 80 90 10 20]

The condition arr != 40 returns a bool array of same size as arr with value True at places where value is not equal to 40 and returns False at other places. Like this

[ False True True True True True False True True False]

When we will pass it to [] of numpy array arr then it will select the elemnts whose value is True. Means it will return the elements from arr which are not  equal to 40.

You can also delete column using numpy delete column tutorial.

Delete elements in Numpy Array based on multiple conditions :

Like above example, it will create a bool array using multiple conditions on numpy array and when it will be passed to [] operator of numpy array to select the elements then it will return a copy of the numpy array satisfying the condition suppose (arr > 40) & (arr < 80) means elements greater than 40 and less than 80 will be returned.

#Program : 

import numpy as np 
# numpy array created from a list 
arr = np.array([40,50,60,70,80,90,40,10,20,40]) 
print('Numpy Array before deleting any element :') 
print(arr) 

# Remove all occurrences of elements below 40 & greater than 80 
# Means keeping elements greater than 40 and less than 80
arr = arr[ (arr > 40) & (arr < 80) ]
print('Modified Numpy Array after deleting elements :') 
print(arr)
Output :
Numpy Array before deleting any element :
[40 50 60 70 80 90 40 10 20 40]
Modified Numpy Array after deleting elements :
[50 60 70]

Delete elements by value or condition using np.argwhere() & np.delete() :

By using np.argwhere() & np.delete()  we can also delete any elements.

#Program : 

import numpy as np 
# numpy array created from a list 
arr = np.array([40,50,60,70,80,90,40,10,20,40]) 
print('Numpy Array before deleting any element :') 
print(arr) 

# deleting all occurrences of element with value 40
arr = np.delete(arr, np.argwhere(arr == 40))
print('Modified Numpy Array after deleting all occurrences of 40') 
print(arr)
Output : 
Numpy Array before deleting all occurrences of 40 : 
[40 50 60 70 80 90 40 10 20 40] 
Modified Numpy Array after deleting all occurrences of 40 : 
[50 60 70 80 90 10 20]

In the above example np.delete() function will delete the element and np.argwhere() function will detect the index.
Means the condition arr == 40 will return a bool array like

[True False False False False False True False False True]

Where the condition arr == 40 matches it returns True and if condition fails it returns False. And when the bool array will be passed inside the function np.argwhere() then it will return the index positions where the values are True.

i.e

[ [0]
  [6]
  [9]]

These are the indices which represents the value 40.

When this index positions will be passed inside np.delete() function then the element present at those index positions will be deleted.

Delete elements by multiple conditions using np.argwhere() & np.delete() :

The concept is same like above only the difference is the elements will be deleted based on multiple conditions.

So, let’s see the implementation of it.

#Program : 

import numpy as np 
# numpy array created from a list 
arr = np.array([40,50,60,70,80,90,40,10,20,40]) 
print('Numpy Array before deleting any element :') 
print(arr) 

#It will delete all the elements which are greater than 40 and less than 80
arr = np.delete(arr, np.argwhere( (arr >= 40) & (arr <= 80) ))
print('Modified Numpy Array after deleting :') 
print(arr)
Output : 
Numpy Array before deleting any element : 
[40 50 60 70 80 90 40 10 20 40] 
Modified Numpy Array after deleting elements : 
[90 10 20]

Solved- TypeError: dict_keys object does not support indexing

Getting and resolving ‘TypeError: dict_keys object does not support indexing in Python’.

In this article we will discuss about

  • Reason of getting ‘TypeError: ‘dict_keys’ object does not support indexing’
  • Resolving the type error.

So let’s start exploring the topic.

To fetch keys, values or key-value pair from a dictionary in python we use functions like keys(), values() and items() which return view object so that we get a dynamic view on the dictionary entries.

The important point is that when dictionary changes then these views reflects these changes and we can iterate over it also. But when we want to use indexing on these objects then it causes TypeError.

Getting TypeError :

#Program :

# Dictionary created of string and int
word_freq = {
    'Aa' : 56,
    "Bb"    : 23,
    'Cc'  : 43,
    'Dd'  : 78,
    'Ee'   : 11
}

# Here, fetching a view object 
# by pointing to all keys of dictionary
keys = word_freq.keys()
print('dict_keys view object:')
print(keys)
print('Try to perform indexing:')

# Here, trying to perform indexing on the key's view object 
# Which will cause error
first_key = keys[0]
print('First Key: ', first_key)
Output :

Try to perform indexing:
Traceback (most recent call last):
File “temp.py”, line 18, in <module>
first_key = keys[0]
TypeError: ‘dict_keys’ object does not support indexing

Here, in the above example we got Type error as because we tryied to select value at index 0 from the dict_keys object, which is a view object and we know view object does not support indexing.

Resolving TypeError :

The solution to TypeError: dict_keys object does not support indexing is very simple. We just need to convert these view object dict_keys into a list and then we can perform indexing on that. Means we will cast the dict_keys object to list object and then selecting elements at any index position.

#Program :

# Dictionary created
word_freq = {
    'Aa' : 10,
    "Bb" : 20,
    'Cc' : 30,
    'Dd' : 40,
    'ee' : 50
}
# Here, fetching a view object 
# by pointing to all keys of dictionary
keys = list(word_freq.keys())
print('List of Keys:')
print(keys)

# Selecting 1st element from keys list
first_key = keys[0]
print('First Key: ', first_key)
Output :
List of Keys:
['Aa', 'Bb', 'Cc', 'Dd', 'Ee']
Second Key: Aa
In this example we converted all the keys of the dictionary to list and then we selected 1st element from the list which is present at index position 0 and it also returned the first key which is present at index position 0.