Python

FuzzyWuzzy Python library

In this post,  let us look at how to use the Python built-in fuzzyWuzzy library to match the string and determine how they are similar using various examples.

Python has a few methods for comparing two strings. A few of the most common methods are listed below.

  • Using Regex
  • Simple Compare
  • Using dfflib

FuzzyBuzzy library in Python:

The FuzzyBuzzy library was created to compare to strings. To compare strings, we have other modules such as regex and difflib. However, FuzzyBuzzy is one-of-a-kind. Instead of true, false, or string, the methods in this library return a score out of 100 based on how well the strings match.

The process of finding strings that match a given pattern is known as fuzzy string matching. To calculate the differences between sequences, it employs Levenshtein Distance.

It is an open-source library developed and released by SeatGeek.

This library can assist in mapping databases that lack a common key, such as joining two tables by company name, which differs in both tables.

Example1:

# Give the string as static input and store it in a variable.
gvn_str1 = "Hello this is btechgeeks"  
# Give the string as static input and store it in a variable.
gvn_str2 = "Hello this is btechgeeks"  

# Check if both the given strings are equal using the if conditional statement
comparision_rslt = gvn_str1 == gvn_str2  
# Print the result of comparision
print(comparision_rslt)

Output:

True

FuzzyWuzzy Python library

Type the below command to install the fuzzywuzzy library:

pip install fuzzywuzzy

Now type the following command:

pip install python-Levenshtein

Method #1: Using Fuzz.ratio() method

The fuzz module is used to compare two strings at the same time. This function returns a score out of 100 after comparison using the various methods.

Fuzz.ratio() function:

It is one of the most important fuzz module methods. It compares the string and assigns a score based on how accurately the given string matches.

Approach:

  • Import fuzz from fuzzywuzzy 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.
  • Check if both the given strings are similar using the fuzz.ratio() function by passing given both strings as arguments to it.
  • Here it returns a score out of 100, which indicates how much percent they are similar out of 100.
  • Similarly, check with other strings and print the result.
  • The Exit of the Program.

Below is the implementation:

# Import fuzz from fuzzywuzzy module using the import keyword
from fuzzywuzzy import fuzz  

# Give the first string as static input and store it in a variable.
gvn_str1 = "Hello this is btechgeeks"  
# Give the second string as static input and store it in another variable.
gvn_str2 = "Hello this is btechgeeks"  

# Check if both the given strings are similar using the fuzz.ratio() function
# by passing given both strings as arguments to it.
# Here it returns a score out of 100, which indicates how much percent 
# they are similar out of 100.
print(fuzz.ratio(gvn_str1, gvn_str2))
  
# Similarly check with other strings and print the result
print(fuzz.ratio('btechgeeks', 'btech geeks'))

print(fuzz.ratio('Hello this is btechgeeks', 'Hello btechgeeks'))

print(fuzz.ratio('Hello this is btechgeeks', 'Welcome'))

Output:

100
95
80
26

Method #2: Using Fuzz.partial_ratio()

Another useful method in the fuzzywuzzy library is partial_ratio(). It handles complex string comparisons such as substring matching.

Below is the implementation:

# Import fuzz from fuzzywuzzy module using the import keyword
from fuzzywuzzy import fuzz  

# Give the string as static input and store it in a variable.
gvn_str1 = "Hello this is btechgeeks"  
# Give the string as static input and store it in a variable.
gvn_str2 = "techgeeks"  

# Check if both the given strings are similar using the fuzz.partial_ratio() function
# by passing given both strings as arguments to it.
# Here it returns a score out of 100, which indicates how much percent 
# they are similar out of 100.
print(fuzz.partial_ratio(gvn_str1, gvn_str2))
  
# Similarly check with other strings and print the result
# Here only the Exclamation mark differs in comparision to both the strings, 
# but partially words are same hence returns 100
print(fuzz.partial_ratio('btechgeeks', 'btechgeeks!'))

print(fuzz.partial_ratio('btechgeeks', 'btech geeks'))

print(fuzz.partial_ratio('Hello this is btechgeeks', 'this is'))

# only partial tokens matches here hence returns 55
print(fuzz.partial_ratio('Hello this is btechgeeks', 'this python'))

Output:

100
100
90
100
55

Method #3: Using Fuzz.token_sort_ratio()

This method does not guarantee an accurate result because we can change the order of the strings. It might not produce an accurate result.

However, the fuzzywuzzy module provides a solution.

Below is the implementation:

# Import fuzz from fuzzywuzzy module using the import keyword
from fuzzywuzzy import fuzz  

# Give the string as static input and store it in a variable.
gvn_str1 = "Hello this is btechgeeks"  
# Give the string as static input and store it in a variable.
gvn_str2 = "this btechgeeks hello is"  

# Check if both the given strings are similar using the fuzz.token_sort_ratio() function
# by passing given both strings as arguments to it.
# Here both the strings are similar but differ in their order of string. 
# Hence it returns 100
print(fuzz.token_sort_ratio(gvn_str1, gvn_str2))

# Similarly check with the other strings and print the result
print(fuzz.token_sort_ratio("Hello this btechgeeks", "Hello this this btechgeeks"))

# Here it returns 100 since the duplicate words are treated as a single word
# by the token_set_ratio() function
print(fuzz.token_set_ratio("Hello this btechgeeks", "Hello this this btechgeeks"))

Output:

100
89
100

Explanation:

Here, we used another method called fuzz.token_set_ratio(), which performs a set operation, extracts the common token, and then performs a ratio() pairwise comparison.

Since the substring or smaller string is made up of larger chunks of the original string or the remaining token is closer to each other, the intersection of the sorted token is always the same.

Method #4: Using process module

If we have a list of options and want to find the closest match/matches we can use the process module to do so.

Below is the implementation:

# Import process module from fuzzywuzzy module using the import keyword
from fuzzywuzzy import process  

# Give the string as static input and store it in a variable.
gvn_string = "Hello betchgeeks"  

# Give the list of options and store it in another variable
gvn_options = ["hello","Hello python","betchgeeks","Python betchgeeks"]  
# Extract the ratios by passing the given string and options to extract() function
ratios_rslt = process.extract(gvn_string, gvn_options)  
print(ratios_rslt)  
# We can choose the string that has highest matching percentage using extractOne() function
most_accurate = process.extractOne(gvn_string, gvn_options)  
print('Most Accurate Result:',most_accurate)

Output:

[('hello', 90), ('betchgeeks', 90), ('Python betchgeeks', 79), ('Hello python', 57)]
Most Accurate Result: ('hello', 90)

Method #5: Using Fuzz.WRatio()

The process module also includes the WRatio, which produces a more accurate result than the simple ratio. It handles lower and upper case, as well as some other parameters.

Below is the implementation:

# Import process module from fuzzywuzzy module using the import keyword
from fuzzywuzzy import process  

# Pass two strings as arguments to the WRatio() function of fuzz module
# to compare both the strings and returns the score
# Here both the strings are similar but differ in their cases(lower/upper)
# The WRatio() function is ignores case-sensitivity, so it returns 100
print(fuzz.WRatio('hello betchgeeks', 'Hello Betchgeeks'))

# Smilarly check for the other strings and print the result
print(fuzz.WRatio('hello betchgeeks', 'hello betchgeeks!!!!'))

# Here we are using the fuzz.ratio() function for the same strings as above
print(fuzz.ratio('hello betchgeeks', 'hello betchgeeks!!!!'))

Output:

100
100
89

How to Get the substring from given string using list slicing in Python?

A substring is a portion of a string. There are several methods in Python for creating a substring and checking if a substring exists in a string, the index of a substring, and more. Let’s take a look at some substring operations.

Slicing

You can extract a substring from a string by slicing with indices that correspond to your substring.

Syntax:

gvn_string[start:stop:step]

Parameters

  • start: Slicing begins at this index of the list.
  • stop: The index of the list at which slicing ends.
  • step: It allows you to select the nth item from start to stop. A number indicating the step of slicing.  The default value is 1.

Python Program to Get the substring from a given string using list slicing

Method #1: Slicing with start and stop values

Approach:

  • Give the string as static input and store it in a variable.
  • Print the given string
  • Create a substring from the start of the string till the required index you want
  • Create a substring from the end of the string
  • Print the substring from the start of the string using slicing.
  • Here printing characters from 0 to 2(excluding the last index).
  • Print the substring from the end of the string using slicing
  • Here printing characters from 4 to the entire string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'hellothisispythonprograms'

# Print the given string 
print("The given string = ", gvn_str)

# create a substring from the start of string till the required index you want 
substr_frm_start = gvn_str[:3]
# create a substring from the end of string 
substr_frm_end = gvn_str[4:]

# Print the substring from the starting of the string using slicing
# here printing charcters from 0 to 2(excluding the last index) 
print("The substring from the starting of the string = ", substr_frm_start)
# Print the substring from the end of the string using slicing
# here printing characters from 4 to entire string
print("The substring from the end of the string = ", substr_frm_end)

Output:

The given string = hellothisispythonprograms
The substring from the starting of the string = hel
The substring from the end of the string = othisispythonprograms

Method #2: Slicing with a step value

Approach:

  • Give the string as static input and store it in a variable.
  • Print the given string
  • Get the substring by taking step value as 3 to the slicing
  • Get the alternative character substring by taking step value as 2
  • Print the substring from the start of the given string with 3 step
  • Print the substring from the given string with alternate characters(step=2).
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'hellothisispythonprograms'
# Print the given string 
print("The given string = ", gvn_str)

# Get the substring by taking step value as 3 to the slicing
substr_withstep3 = gvn_str[::3]
# Get the alternative character substring by taking step value as 2
substr_withstep2 = gvn_str[::2]

# print the substring from the start of the given string with 3 step
print("The substring from the start of the given string with 3 step = ", substr_withstep3)
# print the substring from the given string with alternate characters(step=2)
print("The substring from the given string with alternate characters(step=2)= ", substr_withstep2)

Output:

The given string = hellothisispythonprograms
The substring from the start of the given string with 3 step = hlhiyorrs
The substring from the given string with alternate characters(step=2)= hlohssyhnrgas

Method #3: Slicing with start, stop and step values

Approach:

  • Give the string as static input and store it in a variable.
  • Print the given string
  • Slice from 2nd index to 7 index with alternate characters(because we used step value as 2)
  • Print the resulting substring.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'hellothisispythonprograms'

# Print the given string 
print("The given string = ", gvn_str)

# Slice from 2nd index to 7 index with alternate characters(because we used step value as 2)
sub_string = gvn_str[2:7:2]

# Print the result substring 
print ("The result substring = ", sub_string)

Output:

The given string = hellothisispythonprograms
The result substring = loh

Method #4: Slicing with start, stop and step values (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Print the given string
  • Give the start value as user input using the int(), input() functions and store it in another variable (here int() converts to an integer datatype)
  • Give the end value as user input using the int(), input() functions and store it in another variable
  • Give the step value as user input using the int(), input() functions
    and store it in another variable
  • Slice the given string based on the above-given start, end and step values and store it in another variable
  • Print the resulting substring.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Give some random string = ")

# Print the given string 
print("The given string = ", gvn_str)

# Give the start value as user input using the int(), input() functions
# and store it in another variable (here int() converts to an integer datatype)
gvn_startval = int(input("Give some random start value = "))
# Give the end value as user input using the int(), input() functions
# and store it in another variable 
gvn_endval = int(input("Give some random end value = "))
# Give the step value as user input using the int(), input() functions
# and store it in another variable 
gvn_step = int(input("Give some random step value = "))

# Slice the given string based on the above given start, end and step values  
# and store it in another variable 
sub_string = gvn_str[gvn_startval:gvn_endval:gvn_step]

# Print the result substring 
print ("The result substring = ", sub_string)

Output:

Give some random string = good morning python programs
The given string = good morning python programs
Give some random start value = 1
Give some random end value = 15
Give some random step value = 2
The result substring = odmrigp

Explanation:

Here the string "good morning python programs" is sliced from the 
start index=1(o) to the end index 15(t) with a step value =2 i.e, 
it prints alternative characters

Method #5: Slicing with a step value (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Print the given string
  • Give the step value as user input using the int(), and input() functions and store it in another variable (here int() function converts to an integer datatype).
  • Get the substring by taking the given step value to perform slicing.
  • Print the substring from the input string based on the given step value.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Give some random string = ")
# Print the given string 
print("The given string = ", gvn_str)

# Give the step value as user input using the int(), input() functions
# and store it in another variable (here int() function converts to an integer datatype)
gvn_step = int(input("Give some random step value = "))

# Get the substring by taking the given step value to perform slicing
substr_withstep = gvn_str[::gvn_step]

# print the substring from the input string based on the given step value 
print("The substring from the input string based on the given step value  = ", substr_withstep)

Output:

Give some random string = hellothisispythonprograms
The given string = hellothisispythonprograms
Give some random step value = 2
The substring from the input string based on the given step value = hlohssyhnrgas

Switch Case in Python (Replacement)

Switch case statements

The if statement decides whether or not the condition is true. If the condition is true, the indented expression is evaluated; however, if the condition is false, the indented expression under else is evaluated. When we need to run multiple conditions, we can put as many elif conditions as we need between the if and else conditions. Long if statements that compare a variable to several integral values are replaced by switch case statements.

Switch case statements are a replacement for long if statements that compare a variable to several integral values.

  • The switch statement is a multiway branch statement.
  • It allows you to easily route execution to different parts of code based on the value of the expression.
  • A switch statement is a control statement that allows a value to change execution control.

The following are the benefits of using the Switch Case Statement in the program:

  • It is simpler to debug.
  • Anyone other than the programmer can read the program more easily.
  • It is simpler to understand and also to maintain.
  • It is easier to ensure that all values to be checked are handled.

Replacement of switch case statements in python

Python, unlike any other programming language we’ve used before, lacks a switch or case statement.

In this article let us look at the different methods to implement switch case statements in python:

  • Using dictionary Mapping
  • Using if-else statements
  • Using Classes

Switch Case in Python (Replacement)

Below are the ways to perform switch case in Python:

Method #1: Using Classes

Along with the methods described above for implementing the switch case statement in Python, we can also use Python classes.

A class is an object constructor that has properties and methods. Here we look at the below code of using a class to perform a switch case by creating a switch method within the Python switch class.

Approach:

  • Create a class say SwitchMonths
  • Create a function say month which accepts the month number as an argument
  • Give the default value to print if all the conditions fail
  • Get the attribute value by converting the month number to a string and concatenating with case_ (example case_3)
  • Create functions inside the class for each month
  • Create an object for the above SwitchMonths() class and store it in a variable
  • Call the month() function inside the class using the above object by passing the switch case number(month number) as an argument to it
  • Similarly, do the same for others.
  • The Exit of the Program.

Below is the implementation:

# Create a class say SwitchMonths
class SwitchMonths:
    # Create a function say month which accepts the month number as an argument
    def month(self, month):
        # Give the default value to print if all the conditions fails
        default = "Invalid Month"
        # get the attribute value by converting month number to string and concatenating with case_ (example case_3)
        return getattr(self, 'case_' + str(month), lambda: default)()
    # Create functions inside class for each month
    def case_1(self):
        return "january"

    def case_2(self):
        return "febrauary"

    def case_3(self):
        return "march"

    def case_4(self):
       return "april"

    def case_5(self):
        return "may"

    def case_6(self):
        return "june"
    
    def case_7(self):
        return "july"

    def case_8(self):
        return "august"

# Create an object for the above SwitchMonths() class and store it in a variable
class_object = SwitchMonths()

# Call the month() function inside the class using the above 
# object by passing the switch case number(month number) as an argumet to it
print ("The 4th month is:", class_object.month(4))
# Similarly do the same for other
print ("The 7th month is:", class_object.month(7))

Output:

The 4th month is: april
The 7th month is: july

Method #2: Using if-else statements

If-elif is a shortcut for the if-else chain. We can use the if-elif statement and add an else statement at the end to perform if none of the if-elif statements above are true.

Syntax:

if (condition):
    statement
elif (condition):
    statement
.
.
else:
    statement

Approach:

  • Give the string(website name) as static input and store it in a variable.
  • Check if the given website name is Btechgeeks using the if conditional statement and == operator.
  • If it is true, the print “The given website is Btechgeeks”.
  • Else Again Check if the given website name is Sheetstips using the elif conditional statement
    and == operator.
  • If it is true, the print “The given website is Sheetstips”.
  • Else Again Check if the given website name is PythonPrograms using the elif conditional statement
    and == operator.
  • If it is true, the print “The given website is PythonPrograms”.
  • Else if all the above conditions fail then print some random acknowledgment.
    in an else conditional statement at the end.
  • The Exit of the Program.

Below is the implementation:

# Give the string(website name) as static input and store it in a variable.
gvn_website = 'PythonPrograms'

# Check if the given website name is Btechgeeks using the if conditional statement
# and == operator.
if gvn_website == 'Btechgeeks': 
    # If it is true, the print "The given website is Btechgeeks".
    print("The given website is Btechgeeks") 

# Else Again Check if the given website name is Sheetstips using the elif conditional statement
# and == operator.
elif gvn_website == "Sheetstips": 
    # If it is true, the print "The given website is Sheetstips".
    print("The given website is Sheetstips") 

# Else Again Check if the given website name is PythonPrograms using the elif conditional statement
# and == operator.
elif gvn_website == "PythonPrograms": 
    # If it is true, the print "The given website is PythonPrograms".
    print("The given website is PythonPrograms") 

# Else if all the above conditions fails then print some random acknowledgement 
# in a else conditional statement at the end
else: 
    print("Sorry! It is not a correct website")

Output:

The given website is PythonPrograms

Method #3: Using dictionary Mapping

The dictionary in Python uses key-value pairs to store groups of objects in memory. The key value of the dictionary data type acts as a ‘case’ in a switch case statement when implementing the switch case statement.

Below is the implementation:

def january():
    return "january"
def febrauary():
    return "febrauary"
def march():
    return "march"
def april():
    return "april"
def may():
    return "may"
def june():
    return "june"
def july():
    return "july"
def august():
    return "august"
def september():
    return "september"
def october():
    return "october"
def november():
    return "november"
def december():
    return "december"
def default():
    return "Invalid Month"
# Dictionary to store month values/numbers
switcherDict = {
    1: january,
    2: febrauary,
    3: march,
    4: april,
    5: may,
    6: june,
    7: july,
    8: august,
    9: september,
    10: october,
    11:november,
    12:december
    }

def switch(month): 
    return switcherDict.get(month, default)()

# Passing the value of the month to the switch() function to get month name
print("The 5th month is:", switch(5))
print("The 8th month is:", switch(8))

Output:

The 5th month is: may
The 8th month is: august

 

12 Python In-Built Functions You Should Know

In this article, let us look at the 12 important in-built Functions in Python which helps you to code quickly and easily.

1)append()

The append() function in Python takes a single item as input and appends it to the end of the given list, tuple, or any other set. In Python, append() does not return a new list of items; instead, it returns null. It simply modifies the original list by adding the item at the end.

The length of the list is then increased by one. We can add an item to the list and also add a list to another list. It adds any data type that should be at the end of the list.

Time complexity: O(1).

Syntax:

append(item)

Parameters

  • item: It is the item that is to be added/appended

Example

# Give the list as static input and store it in a variable.
gvn_lst = ["Hello", "this", "is"]

# Pass some random string element as an argument to the append() function 
# and apply it on the given list to add the element at the end of the list
gvn_lst.append("PythonPrograms")

# Print the given list after appending a new list element at the end
print(gvn_lst)

Output:

['Hello', 'this', 'is', 'PythonPrograms']

2)reduce()

The reduce() function in Python iterates through each item in a list or other iterable data type and returns a single value. It is found in the functools library. This is more effective than loop.

Syntax:

reduce(function, iterable)

Parameters

  • function: The function that will be used in the code
  • iterable: The value that will be iterated in the code

Example

# Import reduce() function from functools module using the import keyword
from functools import reduce
def multiply(x, y):
   return x*y
gvn_lst = [2, 3, 5]
print(reduce(multiply, gvn_lst))

Output:

30

3)split():

The split() function is used to split a string into a list of strings by breaking it with the specified separator. The separator can be specified; the default separator is any whitespace.

Syntax:

str.split(separator, maxsplit)

Parameters

  • separator: This is optional. The delimiter at which splits occur. If no separator is specified, the string is split at whitespaces.
  • maxsplit: This is optional. It is the maximum number of splits. There is no limit to the number of splits if it is not provided.

Return Value:

A list of strings is returned by the split() function.

Example

# Give the first string as static input and store it in a variable.
gvn_str1= 'Hello this is pythonprograms'
# Apply split() function on the given first string without 
# passing any separator as an argument
# Here it splits the given string based on the whitespaces by default
print("Splitting gvn_str1:", gvn_str1.split())

# Give the second string as static input and store it in another variable.
gvn_str2 = 'Hello,this,is pythonprograms'

# Apply split() function on the given second string by passing any separator as (,) and maxsplit=1  
# as arguments to it 
# Here it splits the given string containing commas.
# Here 1 specifies we are going to split the first comma as separate element
print("Splitting gvn_str2:", gvn_str2.split(',', 1))

Output:

Splitting gvn_str1: ['Hello', 'this', 'is', 'pythonprograms']
Splitting gvn_str2: ['Hello', 'this,is pythonprograms']

4)Slice():

Based on the specified range, the slice() method returns a portion of an iterable as an object of the slice class. It works with string, list, tuple, set, bytes, or range objects, as well as custom class objects that implement the sequence methods, __getitem__() and __len__().

Syntax:

slice(stop)
slice(start, stop, step)

Parameters

  • start: This is optional. The index at which the iterable’s slicing starts. None is the default value
  • stop: This is the ending index of slicing.
  • step: This is optional. It is the number of steps to jump/increment.

Example

# Give the list as static input and store it in a variable.
gvn_list = [1, 3, 6, 8, 9, 4, 10, 14, 18]


# Pass start, stop as arguments to the slice() function to get the part of the list
# (default stepsize is 1) and store it in a variable.
# Here it returns the list elements in the index range 2 to 6(excluding the last index)
sliceObject_1 = slice(2, 7)

# Pass only the stop value as an argument to the slice() function 
# to get the portion of the list in the given range
# Here start and step values are considered 0, 1 respectively bu default and 
# we get a list elements in the index range 0 to 4
sliceObject_2 = slice(5)

# Slice the given list by passing the start, stop, step values as arguments
# to the slice() function and store it in a variable.
# Here it returnslist elements from index 1 to 7(excluding last index) with the step value 2 
sliceObject_3 = slice(1, 8, 2)
 
# Print the result list elements in the index range 2 to 6
print("The result list elements in the index range 2 to 6: ", gvn_list[sliceObject_1]) 
# Print the result list elements in the index range 0 to 4
print("The result list elements in the index range 0 to 4: ", gvn_list[sliceObject_2])
# Print the result list elements in the index range 1 to 7 with step=2
print("The result list elements in the index range 1 to 7 with step=2: ", gvn_list[sliceObject_3])

Output:

The result list elements in the index range 2 to 6: [6, 8, 9, 4, 10]
The result list elements in the index range 0 to 4: [1, 3, 6, 8, 9]
The result list elements in the index range 1 to 7 with step=2: [3, 8, 4, 14]

5)eval()

The eval() function in Python allows you to perform mathematical operations on integers or floats, even in string form. A mathematical calculation in string format is frequently useful.

The eval() function evaluates the given expression(mathematical or logical). It parses the function, compiles it to bytecode, and then returns the output if a string is passed to it. Because operators have no time complexity, neither does eval.

Syntax:

eval(expression)

Parameters

  • expression: It could be any expression either mathematical or logical

Example

# Give the number as static input and store it in a variable.
gvn_num = 8

# Evaluate the given expression using the eval() function and 
# store it in another variable.
rslt= eval("(gvn_num *9)/2")

# Print the result
print(rslt)

Output:

36.0

6)map()

The map() function, like reduce(), allows you to iterate over each item in an iterable. Map(), on the other hand, operates on each item independently, rather than producing a single result.

Finally, you can use the map() function to perform mathematical operations on two or more lists. It can even be used to manipulate an array of any data type.

Time complexity of the map() = O(n)

Syntax:

map(function, iterable)

Parameters

  • function: The function that will be used in the code
  • iterable: The value that will be iterated in the code
# Create a function which accepts the number as argument and 
# returns the addition of that number with 5 as a result
def add_numbers(gvn_num):
   # Add 5 to the given number and return the result
   return gvn_num+5

# Pass the above add_numbers function and tuple of numbers as arguments to the 
# map() function 
# It will apply the add_numbers function for every element of the list
gvn_num = map(add_numbers, (2, 5, 10, 16))
# Print the result
print(*gvn_num)

Output:

7 10 15 21

7)bin()

The bin() function converts an integer to a binary string prefixing with 0b. Moreover, the integer passed may be negative or positive. For a number n, the time complexity is O(log(n)).

Syntax:

bin(integer)

Parameters

  • integer: It is an integer value passed in order to obtain its binary form.

Example

# Print the binary value of any number by passing it as an argument to the bin() function
# Here we are printing the binary value of 7
print("Binary value of 7 = ", bin(7))

# Here we are printing the binary value of 5
print("Binary value of 5 = ", bin(5))

Output:

Binary value of 7 = 0b111
Binary value of 5 = 0b101

8)enumerate()

The enumerate() function returns the length of an iterable while simultaneously looping through its items. As a result, while printing each item in an iterable data type, it also prints its index.

Assume you want a user to see a list of the items in your database. You can put them in a list and use the enumerate() function to get a numbered list out of it.

Example1

# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "this", "is", "pythonprograms"]

# Loop in the given list with first iterator(i) as index and second iterator as list element value
for i, j in enumerate(gvn_lst):
    print(i, j)

Output:

0 hello
1 this
2 is
3 pythonprograms

Enumerating the list, in addition to being faster, allows you to customize how your numbered items appear.

In fact, by including a start parameter, you can choose to begin numbering from the number you want rather than zero.

Example2

# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "this", "is", "pythonprograms"]

# Pass the given list, start value(from where you want to begin the index number) 
# as arguments to the enumerate() function 
for i, j in enumerate(gvn_lst, start=5):
    print(i, j)

Output:

5 hello
6 this
7 is
8 pythonprograms

9)filter()

The filter() function creates a new iterator that filters elements from an existing one (like list, tuple, or dictionary).

It checks whether the given condition is present in the sequence or not and then prints the result.

Time complexity = O(n).

Syntax:

filter(function, iterable)

Parameters

  • function: The function that will be used in the code
  • iterable: The value that will be iterated in the code
# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "this", "is", "pythonprograms"]
 
   
def vowels(x):
  # Checking whether the first character is vowel
  return x[0].lower() in 'aeiou'

elements = filter(vowels, gvn_lst)

print(list(elements))

Output:

['is']

10)strip()

Strip() in Python removes leading characters from a string. It removes the first character from the string repeatedly if it matches any of the provided characters.

If no character is specified, the strip removes all leading whitespace characters from the string.

# Give the string as static input and store it in a variable.
gvn_str = "pythonprograms"
# Pass a charcter to be stripped/removed from a given as an argument
# to the strip() function and print the result.
# Here it removes/strips the first p character from the given string
rslt = gvn_str.strip("p")
print(rslt)

Output:

ythonprograms

11)exec()

The exec() function executes the specified condition and returns the result in Python expression form.

The Python exec() function runs a dynamically created program, which can be a string or a code object. If it is a string, it is parsed as a Python statement and executed; otherwise, a syntax error is produced.

Syntax:

exec(object[, globals[, locals]])

Parameters

  • object: It could be a string or object code.
  • globals: This is optional. It could be a dictionary.
  • locals: This is optional. It could be a mapping object.

Example

# Give the number as static input and store it in a variable.
gvn_num = 5
# Multiply the given number with 10 and pass it as a string to the exec()
# function to execute the given condition
exec('print(gvn_num*10)')

Output:

50

12)sorted()

The sorted() function returns a sorted list of the given iterable object.

You can sort either in ascending or descending order by specifying it. Numbers are sorted numerically, while strings are sorted alphabetically.

Syntax:

sorted(iterable, key=key, reverse=False)

Parameters

  • iterable: This is required. It could be any sequence to be sorted like list, dictionary, tuple, etc.
  • key: This is optional. It is a function to execute to decide the order. None is the default value.
  • reverse: This is optional. A Boolean expression. True sorts in ascending, False sorts in descending order. The default value is False.

Example1: Sorting the given list of strings in ascending order

# Give the list of strings as static input and store it in a variable.
gvn_lst = ["r", "c", "e", "h", "v", "s"]

# Pass the given list as an argument to the sorted() function to sort the 
# given list in ascending order alphabetically. 
sorted_lst = sorted(gvn_lst)
# Print the given list after sorting
print("The given list after sorting = ", sorted_lst)

Output:

The given list after sorting = ['c', 'e', 'h', 'r', 's', 'v']

Example2: Sorting the given list of strings in descending order

# Give the list of strings as static input and store it in a variable.
gvn_lst = ["r", "c", "e", "h", "v", "s"]

# Pass the given list, reverse=True as arguments to the sorted() function to sort the 
# given list in descending order alphabetically. 
sorted_lst = sorted(gvn_lst, reverse=True)
# Print the given list after sorting in descending order
print("The given list after sorting in descending order = ", sorted_lst)

Output:

The given list after sorting in descending order = ['v', 's', 'r', 'h', 'e', 'c']

Example3: Sorting the given list of numbers in descending order

# Give the list of numbers as static input and store it in a variable.
gvn_lst = [1, 34, 6, 10, 2, 25, 80]

# Pass the given list, reverse=True as arguments to the sorted() function to sort the 
# given list of numbers in descending order. 
sorted_lst = sorted(gvn_lst, reverse=True)
# Print the given list after sorting in descending order
print("The given list after sorting in descending order = ", sorted_lst)

Output:

The given list after sorting in descending order = [80, 34, 25, 10, 6, 2, 1]

self in Python class

In this article, let us look at what is a self in python class along with some examples to understand the self more clearly.

When we write a class in Python, we need a way to access its attributes and methods. Most languages have a fixed syntax for referring to attributes and methods; C++, for example, uses this for reference.

What is self in Python class?

The self in class is used to represent the instance of the class. In Python, you can access the attributes and methods of the class using this keyword. It binds the attributes with the arguments provided. We use self because Python does not use the ‘@’ syntax to refer to instance attributes. In Python, there are methods that cause the instance to be passed but not received automatically.

Self is always points to the Current Object

self in Python class

Showing the address of self and object

Approach:

  • Create a class say checkSelf.
  • In the constructor, we print the value of self.
  • Create an object for the above class (Here self referes to the this object)
  • Print the id of the above created about using the id() function.
  • The Exit of the Program.

Below is the implementation:

# Here we can observe that the self and rslt_object is referring to the same object
# Create a class say checkSelf
class checkSelf:
  # In the constructor we print the value of self
    def __init__(self):
        print("The Address/Id of self: ", id(self))
        
# Create an object for the above class (Here self referes to the this object)
rslt_object = checkSelf()
# Print the id of the above created about using the id() function
print("The Address/Id of a checkSelf class object: ",id(rslt_object))

Output:

The Address/Id of self: 139973697862096
The Address/Id of a checkSelf class object: 139973697862096

Explanation:

Here we can observe that the self and rslt_object is referring to the
same object. We can see the address of the self and the address of 
the object are the same.

Method #1: Using self to call the methods

Approach:

  • Create a class say Employ
  • Create a init constructor by passing self, employName, employId as arguments to it
  • Initialize the instance variables
  • Create a method say showEmployId which prints the employ id using self
  • Create another method say showEmployName which prints the employ name using self
  • Create a method say showEmployDetails which calls both the methods using self showEmployName(), showEmployId().
  • Create an Instance/object of the above-created Employ class.
  • Call the above method showEmployDetails() using the above employ Object.
  • The Exit of the Program.

Below is the implementation:

# Create a class say Employ
class Employ():

    # Create a init constructor by passing self, employName, employId as arguments to it
    def __init__ (self, employName, employId):
        # Initilaize the instance variables
        self.employName = employName
        self.employId = employId

    # Create a method say showEmployId which prints the employ id using self
    def showEmployId(self):
        print("Employ Id = ", self.employId)
    
    # Create another method say showEmployName which prints the employ name using self
    def showEmployName(self):
        print("Employ Name = ", self.employName)
    
    # Create a method say showEmployDetails which calls both the methods using self
    # showEmployName, showEmployId
    def showEmployDetails(self):
        self.showEmployName()
        self.showEmployId()

# Create an Instance/object of the above created Employ class 
employObj = Employ("John", 2122)

# Call the above method showEmployDetails() using the above employ Object
employObj.showEmployDetails()

Output:

Employ Name = John
Employ Id = 2122

Explanation:

  • Here all the methods of the class have self as the first parameter.
  • The self is used to call the attributes employName and employId.
  • Here, the self is used to call the methods showEmployId() and showEmployName().

NOTE

The term self is not a keyword; rather, it is a Python developer convention.
You can substitute any other word for the first parameter and it will 
still work. However, it is preferable to use self rather than anything 
else because it enhances code readability.

Method #2: Replacing self with some other name

In function, self is a parameter that can be replaced with a different parameter name.

Here we replace self with hello in the above example. Still, it works fine.

Approach:

  • Create a class say Employ
  • Create a init constructor by passing employName, employId as arguments to it using hello instead of self
  • Initilaize the instance variables
  • Create a function say showEmployId which prints the employ id using hello instead of self
  • Create another function say showEmployName which prints the employ name using hello instead of self
  • Create a function say showEmployDetails which calls both the functions showEmployName(), showEmployId() using hello instead of self.
  • Create an Instance/object of the above created Employ class
  • Call the above function showEmployDetails() using the above employ Object.
  • The Exit of the Program.

Below is the implementation:

# Create a class say Employ
class Employ():

    # Create a init constructor by passing employName, employId as 
    # arguments to it using hello instead of self
    def __init__ (hello, employName, employId):
        # Initilaize the instance variables
        hello.employName = employName
        hello.employId = employId

    # Create a function say showEmployId which prints the employ id
    # using hello instead of self
    def showEmployId(hello):
        print("Employ Id = ", hello.employId)
    
    # Create another function say showEmployName which prints the employ name
    # using hello instead of self
    def showEmployName(hello):
        print("Employ Name = ", hello.employName)
    
    # Create a function say showEmployDetails which calls both the functions 
    # showEmployName, showEmployId using hello instead of self
    def showEmployDetails(hello):
        hello.showEmployName()
        hello.showEmployId()

# Create an Instance/object of the above created Employ class 
employObj = Employ("John", 2122)

# Call the above function showEmployDetails() using the above employ Object
employObj.showEmployDetails()

Output:

Employ Name = John
Employ Id = 2122

Method #3: Without Providing self Parameter

The Instance method and constructor, self must be provided as a First parameter. It will result in an error if you do not provide it.

# Here we can observe that the self is not passed as the first parameter
# in the init constructor. Hence it throws an error

# Create a class say checkwithoutSelf
class checkwithoutSelf:
  # In the init constructor we don't pass the self 
    def __init__():
        print("hello this is python programs")

# Create an object for the above class 
rslt_object = checkwithoutSelf()
print("Welcome")

Output:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-43-394e0a56a3d8> in <module>
9 
10 # Create an object for the above class
---> 11 rslt_object = checkwithoutSelf()
12 print("Welcome")

TypeError: __init__() takes 0 positional arguments but 1 was given

 

Avoiding quotes while printing strings in Python

In Python, there are several methods for removing quotes from a string. You may need to remove all quotes or only those that surround a string. You may need to remove single or double quotes as well.

If we print a given list of strings as is, we must use quotes and properly fill in a pair of matching quotes. We can avoid using quotes in print statements.

In this article let us look at how to remove these quotes on strings using the below-given methods:

  • Using join() Function
  • Using the print() & sep keyword

Avoiding quotes while printing strings in Python

Method #1: Using join() function (Static Input)

Join(sequence) joins elements and returns the combined string. Every element of the sequence is combined using the join methods.
A sequence is passed as an argument to the join method. The sequence is written as a single argument: you must surround it with brackets.

You can pass a variable containing the sequence as an argument if you want. This improves readability.

The join() method joins all items in an iterable into a single string.

As the separator, a string must be specified.

Syntax:

string.join(iterable)

Parameters:

iterable: This is required. Any iterable object whose returned values are all strings.

Approach:

  • Give the list of strings as static input and store it in a variable.
  • Print the given list
  • Remove the quotes for the strings in a given list using the join() function by passing the given list as an argument to it by specifying the separator as comma(,) delimiter.
  • The Exit of the Program.

Below is the implementation:

# Give the list of strings as static input and store it in a variable.
gvn_lst = ['Hello', 'this', 'is', 'PythonPrograms']

# Print the given list
print ("The given list = ", gvn_lst)

# Remove the quotes for the strings in a given list using the join() function
# by passing the given list as an argument to it.
print ("The given list after removing quotes on strings: ")
print (', '.join(gvn_lst))

Output:

The given list = ['Hello', 'this', 'is', 'PythonPrograms']
The given list after removing quotes on strings: 
Hello, this, is, PythonPrograms

Method #2: Using join() Function (User Input)

Approach:

  • Give the list of strings as user input using the list(),map(),split(),str functions and store it in a variable.
  • Print the given list.
  • Remove the quotes for the strings in a given list using the join() function by passing the given list as an argument to it by specifying the separator as comma(,) delimiter.
  • The Exit of the Program.

Below is the implementation:

# Give the list of strings as user input using the list(),map(),split(),str
# functions and store it in a variable.
gvn_lst = list(map(str, input(
   'Enter some random List Elements separated by spaces = ').split()))

# Print the given list
print ("The given list = ", gvn_lst)

# Remove the quotes for the strings in a given list using the join() function
# by passing the given list as an argument to it.
print ("The given list after removing quotes on strings: ")
print (', '.join(gvn_lst))

Output:

Enter some random List Elements separated by spaces = Welcome to pythonprograms
The given list = ['Welcome', 'to', 'pythonprograms']
The given list after removing quotes on strings: 
Welcome, to, pythonprograms

Method #3: Using the print() & sep keyword (Static Input)

Approach:

  • Give the list of strings as static input and store it in a variable.
  • Print the given list
  • Remove the quotes for the strings in a given list by passing the separator as comma(,) as delimiter and print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the list of strings as static input and store it in a variable.
gvn_lst = ['Hello', 'this', 'is', 'PythonPrograms']

# Print the given list
print ("The given list = ", gvn_lst)

# Remove the quotes for the strings in a given list by passing the
# separator as comma(,) as delimiter and print the result 
print ("The given list after removing quotes on strings: ")
print(*gvn_lst, sep =', ')

Output:

The given list = ['Hello', 'this', 'is', 'PythonPrograms']
The given list after removing quotes on strings: 
Hello, this, is, PythonPrograms

Method #4: Using the print() & sep keyword (User Input)

Approach:

  • Give the list of strings as user input using the list(),map(),split(),str functions and store it in a variable.
  • Print the given list.
  • Remove the quotes for the strings in a given list by passing the separator as comma(,) as delimiter and print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the list of strings as user input using the list(),map(),split(),str
# functions and store it in a variable.
gvn_lst = list(map(str, input(
   'Enter some random List Elements separated by spaces = ').split()))

# Print the given list
print ("The given list = ", gvn_lst)

# Remove the quotes for the strings in a given list by passing the
# separator as comma(,) as delimiter and print the result 
print ("The given list after removing quotes on strings: ")
print(*gvn_lst, sep =', ')

Output:

Enter some random List Elements separated by spaces = Welcome to pythonprograms
The given list = ['Welcome', 'to', 'pythonprograms']
The given list after removing quotes on strings: 
Welcome, to, pythonprograms

Method Overriding in Python

In this tutorial, let us look at what is method overriding in python along with examples, and its key features.

Method overriding in Python:

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).

parent class: The class that is being inherited is known as the Parent or Superclass.

child class: The class that inherits the parent class’s properties and methods is known as the Child or Subclass.

Features of Method overriding

  • The concept of method overriding is derived from object-oriented programming(OOPS).
  • It allows us to change the implementation of a function in the child class that is defined in the parent class.
  • It is a part of the inheritance concept.
  • Method overriding avoids code duplication while also improving the code by adding some extra properties.

Method overriding Prerequisites 

In Python, there are some prerequisites for method overriding. They are:

  • Method overriding is not possible within a class. As a result, we must derive a child class from a parent class. So, inheritance is required.
  • The method’s name must be the same as in the parent class.
  • The method’s parameters must be the same as those in the parent 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

Method overriding with Multiple Inheritance

Multiple inheritance occurs when a class is derived from one or more parent(base) classes, inheriting all of its properties.

Overriding in Multiple Inheritance occurs when a child class provides its own implementation of methods/attributes while inheriting them from its parent/parents.

Approach:

  • Create a parent class say Vehicle.
  • Inside the class, create a function say vehicletype.
  • Create another function say brand.
  • Create a class say Twowheeler which inherits properties from the parent class Vehicle.
  • Create another class say Threewheeler which inherits properties from the parent class Vehicle.
  • Create another child class say Fourwheeler which inherits properties from the above both the child classes Twowheeler and Threewheeler.
  • Create an object for the last child class Fourwheeler.
  • Call the vehicletype() function from the Vehicle class and print the result.
  • Call the brand() function from the Vehicle class and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a parent class say Vehicle
class Vehicle:
    # Inside the class, create a function say vehicletype
    def vehicletype(self):
        print("This gives the type of vehicle")
    # create another function say brand
    def brand(self):
        print("It gives the brand of vehicle")

# Create class say Twowheeler which inherits properties 
# from the parent class Vehicle
class Twowheeler (Vehicle): 
    def vehicletype(self):
        print("Bike is a type of Twowheeler")

# Create another class say Threewheeler which inherits properties 
# from the parent class Vehicle
class Threewheeler (Vehicle): 
    def vehicletype(self):
        print("Auto is a type of Threewheeler")

# Create another child class say Fourwheeler which inherits properties 
# from the above both the child classes Twowheeler and Threewheeler     
class Fourwheeler (Twowheeler, Threewheeler): 
    def vehicletype(self):
        print("Car is a type of Fourwheeler")
        
# Create an object for the last child class Fourwheeler
obj = Fourwheeler() 

# call the vehicletype() function from the Vehicle class and print the result
obj.vehicletype() 
# call the brand() function from the Vehicle class and print the result
obj.brand()

Output:

Car is a type of Fourwheeler
It gives the brand of vehicle

Method overriding with Multi-level Inheritance

Features from both the base and derived classes are inherited into the new derived class in multilevel inheritance. This is comparable to a child and grandfather relationship.

Approach:

  • Create a parent class say Vehicle.
  • Inside the class, create a function say vehicletype.
  • Create another function say brand.
  • Create a child class say Twowheeler which inherits properties from the parent class Vehicle.
  • Create another child class say Threewheeler which inherits properties from the first child class Twowheeler.
  • Create an object for the last child class Threewheeler.
  • Call the vehicletype() function from the Vehicle class and print the result.
  • Call the brand() function from the Vehicle class and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a parent class say Vehicle
class Vehicle:

    # Inside the class, create a function say vehicletype
    def vehicletype(self):
        print("This gives the type of vehicle")
    # create another function say brand
    def brand(self):
        print("It gives the brand of vehicle")

# Create a child class say Twowheeler which inherits properties 
# from the parent class Vehicle
class Twowheeler(Vehicle): 
    def vehicletype(self):
        print("Bike is a type of Twowheeler")

# Create another child class say Threewheeler which inherits properties 
# from the first child class Twowheeler
class Threewheeler(Twowheeler): 
    def vehicletype(self):
        print("Auto is a type of Threewheeler")

# Create an object for the last child class Threewheeler
obj = Threewheeler() 

# call the vehicletype() function from the Vehicle class and print the result
obj.vehicletype() 
# call the brand() function from the Vehicle class and print the result
obj.brand() 

Output:

Auto is a type of Threewheeler
It gives the brand of vehicle

 

Python slice() function

In this article we are going to discuss about the slice() function in python with examples.

slice() function in Python:

Based on the specified range, the slice() method returns a portion of an iterable as an object of the slice class. It works with string, list, tuple, set, bytes, or range objects, as well as custom class objects that implement the sequence methods, __getitem__() and __len__().

Syntax:

slice(stop)
slice(start, stop, step)

Parameters

  • start: This is optional. The index at which the iterable’s slicing starts. None is the default value
  • stop: This is the ending index of slicing.
  • step: This is optional. It is the number of steps to jump/increment.

Python slice() function

Method #1: Using slice() function on Strings

Approach:

  • Give the string as static input and store it in a variable.
  • Slice the given string using the slice() function by passing start, and stop values as arguments to it (default step size is 1).
  • Here it returns the string in the index range of 2 to 9(excluding the last index).
  • Print the result string after slicing.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'Hello this is PythonPrograms'
# Slice the given string using the slice() function by passing start, stop 
# values as arguements to it(default stepsize is 1)
# Here it returns the string in the index range 2 to 9(excluding the last index)
# NOTE: It also considers the space as an index value
sliceObj = slice(2, 10)

# Print the result string after slicing
print("The result string after slicing = ", gvn_str[sliceObj])

Output:

The result string after slicing = llo this

NOTE:

 It also considers the space as an index value

If only one parameter is specified, start and step are assumed to be None.

# Give the string as static input and store it in a variable.
gvn_str = 'Hello this is PythonPrograms'

# Pass only the stop value as an argument to the slice() function 
# to get the portion of the string in the given range
# Here start and step values are considered 0, 1 respectively and 
# we get a string in the index range 0 to 9
sliceObject_1 = slice(10)

# Slice the given string by passing the start, stop, step values as arguments
# slice() function and  store it in a variable.
# Here it returns the string from index 1 to 13(excluding last index) with the step value 2 
sliceObject_2 = slice(1, 14, 2)
 
# Print the  result string 1 after slicing
print("The result string in the index range 0 to 9: ", gvn_str[sliceObject_1])
# Print the  result string 1 after slicing
print("The result string in the index range 1 to 13 with step=2: ", gvn_str[sliceObject_2])

Output:

The result string in the index range 0 to 9: Hello this
The result string in the index range 1 to 13 with step=2: el hsi

Method #2: Using slice() function on Lists

Approach:

  • Give the list as static input and store it in a variable.
  • Pass start, and stop as arguments to the slice() function to get the part of the list (default stepsize is 1) and store it in a variable.
  • Here it returns the list elements in the index range 2 to 6(excluding the last index)
  • Pass only the stop value as an argument to the slice() function to get the portion of the list in the given range.
  • Here start and step values are considered 0, 1 respectively by default and
    we get a list of elements in the index range of 0 to 4
  • Slice the given list by passing the start, stop, and step values as arguments to the slice() function and storing it in a variable.
  • Here it returns list elements from index 1 to 7(excluding the last index) with the step value 2
  • Print the result list elements in the index range 2 to 6
  • Print the result list elements in the index range 0 to 4
  • Print the result list elements in the index range 1 to 7 with step=2.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_list = [1, 3, 6, 8, 9, 4, 10, 14, 18]


# Pass start, stop as arguments to the slice() function to get the part of the list
# (default stepsize is 1) and store it in a variable.
# Here it returns the list elements in the index range 2 to 6(excluding the last index)
sliceObject_1 = slice(2, 7)

# Pass only the stop value as an argument to the slice() function 
# to get the portion of the list in the given range
# Here start and step values are considered 0, 1 respectively bu default and 
# we get a list elements in the index range 0 to 4
sliceObject_2 = slice(5)

# Slice the given list by passing the start, stop, step values as arguments
# to the slice() function and store it in a variable.
# Here it returnslist elements from index 1 to 7(excluding last index) with the step value 2 
sliceObject_3 = slice(1, 8, 2)
 
# Print the result list elements in the index range 2 to 6
print("The result list elements in the index range 2 to 6: ", gvn_list[sliceObject_1]) 
# Print the result list elements in the index range 0 to 4
print("The result list elements in the index range 0 to 4: ", gvn_list[sliceObject_2])
# Print the result list elements in the index range 1 to 7 with step=2
print("The result list elements in the index range 1 to 7 with step=2: ", gvn_list[sliceObject_3])

Output:

The result list elements in the index range 2 to 6: [6, 8, 9, 4, 10]
The result list elements in the index range 0 to 4: [1, 3, 6, 8, 9]
The result list elements in the index range 1 to 7 with step=2: [3, 8, 4, 14]

Method #3: Using slice() function on Tuples

# Give the list as static input and store it in a variable.
gvn_tuple = (1, 3, 6, 8, 9, 4, 10, 14, 18)


# Pass start, stop as arguments to the slice() function to get the part of the 
# given tuple(default stepsize is 1) and store it in a variable.
# Here it returns the tuple elements in the index range 2 to 6(excluding the last index)
sliceObject_1 = slice(2, 7)

# Pass only the stop value as an argument to the slice() function 
# to get the portion of the tuple in the given range
# Here start and step values are considered 0, 1 respectively by default and 
# we get a tuple elements in the index range 0 to 4
sliceObject_2 = slice(5)

# Slice the given tuple by passing the start, stop, step values as arguments
# to the slice() function and store it in a variable.
# Here it returns the tuple elements from index 1 to 7(excluding last index)
# with the step value 2 
sliceObject_3 = slice(1, 8, 2)
 
# Print the result tuple elements in the index range 2 to 6
print("The result tuple elements in the index range 2 to 6: ", gvn_tuple[sliceObject_1]) 
# Print the result tuple elements in the index range 0 to 4
print("The result tuple elements in the index range 0 to 4: ", gvn_tuple[sliceObject_2])
# Print the result tuple elements in the index range 1 to 7 with step=2
print("The result tuple elements in the index range 1 to 7 with step=2: ", gvn_tuple[sliceObject_3])

Output:

The result tuple elements in the index range 2 to 6: (6, 8, 9, 4, 10)
The result tuple elements in the index range 0 to 4: (1, 3, 6, 8, 9)
The result tuple elements in the index range 1 to 7 with step=2: (3, 8, 4, 14)

Method #4: Using Negative Indexing

Python supports “indexing from the end,” or negative indexing.
This means that the last value in a sequence has a -1 index, the second last has a -2 index, etc.
If you wish to select values from the end (right side) of an iterable, you can use negative indexing.

Negative sequence indexes in Python represent positions from the array’s end. The slice() function can return negative values. In that case, the iteration will be performed backward, from end to start.

# Slicing the given list using negative indexing
# Here -1 represents the last element of the list 
gvn_list = [1, 3, 6, 8, 9, 4, 10, 14, 18]
sliceObject = slice(-1, -4, -1)
print("Slicing the given list = ", gvn_list[sliceObject])

# Slicing the given string using negative indexing
gvn_string = "Pythonprograms"
sliceObject = slice(-1)
print("Slicing the given string = ", gvn_string[sliceObject])

# Slicing the given tuple using negative indexing
gvn_tuple = (1, 3, 6, 8, 9, 4, 10)
sliceObject = slice(-1, -6, -2)
print("Slicing the given tuple = ", gvn_tuple[sliceObject])

Output:

Slicing the given list = [18, 14, 10]
Slicing the given string = Pythonprogram
Slicing the given tuple = (10, 9, 6)

 

 

Python OOPs Concepts

Object-oriented Programming (OOPs) is a programming paradigm in Python that employs objects and classes. It aims to incorporate real-world entities such as inheritance, polymorphisms, encapsulation, and so on into programming. The main idea behind OOPs is to bind the data and the functions that work on it as a single unit so that no other part of the code can access it.

The object is associated with real-world entities such as a book, a house, a pencil, and so on. The oops concept is concerned with writing reusable code. It is a common technique for solving problems by creating objects.

Fundamental Concepts of Object-oriented Programming (OOPs)

  • Class
  • Object
  • Method
  • Inheritance
  • Polymorphism
  • Data Abstraction
  • Encapsulation

Python OOPs Concepts

Class

A class is a collection of objects, or a blueprint of objects that defines the common attributes and methods. The question now is, how do you do that?

It logically groups the data in such a way that code reusability is made simple. Consider an office going ’employee’ as a class and all the attributes related to it like ’empName,’ ’empAge,’ ’empSalary,’ and ’empId’ as Python objects.

Syntax:

class ClassName: 
<statement-1> 
.

.
<statement-N>

Example: Create an empty class

# Create an empty class say Btechgeeks
class Pythonprograms:
    pass

Object

The object is an entity that has a state and behavior. The object is a stateful entity with behaviour. It could be any real-world object, such as a mouse, keyboard, chair, table, pen, etc.

In Python, everything is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the docstring defined in the function source code.

When we define a class, we must create an object to allocate memory.

An object is made up of:

  • state: The state is represented by the attributes of an object. It also reflects an object’s properties.
  • behavior: The behavior is represented by the methods of an object. It also represents an object’s response to other objects.
  • Identity: It gives an object a unique name and allows it to interact with other objects.

Let us consider the class dog to better understand its state, behaviour, and identity:

  • The identity can be thought of as the dog’s name.
  • The breed, age, and color of the dog are examples of state or attributes.
  • The behavior can be used to determine whether the dog is eating or sleeping.

Example

# create a class say Employ
class Employ:  
    def __init__(self, empName, empId):  
        self.empName = empName  
        self.empId = empId  
    def displayEmpDetails(self):  
        print(self.empName,self.empId)  

# calling the Employ class by passing the empName, empId as arguments
emp_object = Employ("Nick", 2122)  
# Display the employ details by calling the displayEmpDetails()
# method using the emp_object
emp_object.displayEmpDetails()  

Output:

Nick 2122

Method

A method is a function that is linked to an object. A method in Python is not unique to class instances. Methods can exist on any object type.

__init__ method:

The __init__ method is similar to C++ and Java constructors. It is executed whenever a class object is instantiated. The method is useful for performing any initialization on your object.

Inheritance

The most important aspect of object-oriented programming is inheritance, which simulates the real-world concept of inheritance. It specifies that the child object inherits/acquires all of the parent object’s properties and behaviors.

We can use inheritance to create a class that inherits all of the properties and behavior of another class. The new class is referred to as a derived class or child class, while the class whose properties are acquired is referred to as a base class or parent class.

It ensures that the code can be reused.

There are 4 types of inheritance in python. They are:

1)Single Inheritance:

A derived class can inherit characteristics from a single-parent class through single-level inheritance.

# Create a parent calss say Employ()
class Employ():
  def __init__(self, empName, empId):  
    self.empName = empName
    self.empId = empId

# Create a child calss say EmployChildClass()
class EmployChildClass(Employ):
  def __init__(self, empName, empId, empRole):
    self.empName = empName
    self.empId = empId
    self.empRole = empRole

# Calling the above Employ parent class by passing empName, empId, empRole
# as arguments to it
emp_object = Employ('Isha', 2122)

# Printing the empId using the emp_object
print(emp_object.empId)

Output:

2122

2)Multi-level Inheritance:

Multi-level inheritance allows a derived class to inherit properties from an immediate parent class, which in turn inherits properties from his parent class.

# Create a parent calss say Employ()
class Employ():
  def __init__(self, empName, empId):  
    self.empName = empName
    self.empId = empId

# Create a first child class say EmployChildClass_1() 
# inheriting properties from parent class Employ
class EmployChildClass_1(Employ):
  def __init__(self, empName, empId):  
    self.empName = empName
    self.empId = empId

# Create a second child class say EmployChildClass_2() 
# inheriting properties from first child class EmployChildClass_1 
class EmployChildClass_2(EmployChildClass_1):
   def __init__(self, empName, empId):  
    self.empName = empName
    self.empId = empId

employ_1 = Employ('Nick', 2122)
employ_2 = EmployChildClass_1('John', 2123)
 
print(employ_1.empId)
print(employ_2.empId)

Output:

2122
2123

3)Hierarchical Inheritance:

More than one derived class can inherit properties from a parent class using hierarchical-level inheritance.

# Create a parent calss say Employ()
class Employ():
  def __init__(self, empName, empId):  
    self.empName = empName
    self.empId = empId

# Create a first child class say EmployChildClass_1() 
# inheriting properties from parent class Employ
class EmployChildClass_1(Employ):
  def __init__(self, empName, empId):  
    self.empName = empName
    self.empId = empId

# Create a second child class say EmployChildClass_2() 
# inheriting properties from parent class Employ
class EmployChildClass_2(Employ):
   def __init__(self, empName, empId):  
    self.empName = empName
    self.empId = empId

employ_1 = Employ('Nick', 2122)
employ_2 = Employ('John', 2123)
 
print(employ_1.empId)
print(employ_2.empId)

Output:

2122
2123

4)Multiple Inheritance:

Multiple inheritance allows a single derived class to inherit properties from multiple base classes.

# Create a parent class say Employ_1()
class Employ_1():
    def __init__(self, empName, empId):  
      self.empName = empName
      self.empId = empId

# Create another parent class say Employ_2()
class Employ_2():
    def __init__(self, empName, empId, empRole):
      self.empName = empName
      self.empId = empId
      self.empRole = empRole
 
# Create a child class say EmployChildClass() 
# inheriting properties from both the parent classes
class EmployChildClass(Employ_1, Employ_2):
    def __init__(self, empName, empId, empRole):
      self.empName = empName
      self.empId = empId
      self.empRole = empRole

employ1 = Employ_1('Nick', 2122)
employ2 = Employ_2('John', 2123, 'Analyst')
 
print(employ1.empId)
print(employ2.empRole)

Output:

2122
Analyst

Polymorphism

Polymorphism is derived from the Greek words poly (many) and morphism (forms). That is, the same function name can be used for many types. This makes programming more intuitive and simple.

Polymorphism means that the same task can be performed in different ways. For example, suppose you have a class animal and all of the animals speak. But they communicate in different ways. In this case, the “speak” behavior is polymorphic and varies depending on the animal. So, while the abstract concept of “animal” does not actually “speak,” specific animals (such as dogs and cats) have a concrete implementation of the action “speak.”

A child class inherits all of the parent class’s methods. In other cases, however, the method inherited from the parent class does not fully fit into the child class. In such circumstances, you must re-implement the method in the child class.

Example

# Create a parent class say Vehicle
class Vehicle:

    def introduction(self):
        print("Vehicles have different models")

    def categories(self):
        print("some are two-wheelers and some four-wheelers etc")

# Create a child class say Car() inheriting properties the parent class Vehicle
class Car(Vehicle):

    def categories(self):
        print("Car is a four-wheeler")

# Create another child class say Bike() inheriting properties the parent class Vehicle
class Bike(Vehicle):

    def categories(self):
        print("Bike is a two-wheeler")

Vehicle_object = Vehicle()
Car_object = Car()
Bike_object = Bike()

Vehicle_object.introduction()
Vehicle_object.categories()
print()
Car_object.introduction()
Car_object.categories()
print()
Bike_object.introduction()
Bike_object.categories()

Output:

Vehicles have different models
some are two-wheelers and some four-wheelers etc

Vehicles have different models
Car is a four-wheeler

Vehicles have different models
Bike is a two-wheeler

Polymorphism is classified into two types:

  • Compile-time Polymorphism.
  • Run-time Polymorphism

Compile-time Polymorphism:

A compile-time polymorphism, also known as a static polymorphism, is one that is resolved during the program’s compilation. “Method overloading” is a common example.

Run-time Polymorphism:

A running time Polymorphism is also known as dynamic polymorphism because it is resolved during the run time. “Method overriding” is a common example of Run-time polymorphism.

Encapsulation

Encapsulation is the process of wrapping up variables and methods into a single entity. It is a fundamental idea in object-oriented programming (OOP). It works as a protective shield, limiting direct access to variables and methods and preventing accidental or unauthorized data alteration. Encapsulation also turns objects into more self-sufficient, self-contained (independently functioning)units.

Real-time Example

Consider the following real-world example of encapsulation. A company has various sections, such as the accounts and finance sections. The finance department controls all financial transactions and data. The sales department is also in charge of all sales-related activities. They keep track of every sale. A finance officer may require full sales data for a certain month at times. He is not permitted to see the data from the sales area in this case. He must first call another officer in the sales unit to request the data. This is called encapsulation.

Access Modifiers in Encapsulation

While programming, it may be necessary to restrict or limit access to particular variables or functions. This is where access modifiers come into play.

When it comes to access, there are three types of access specifiers that can be utilised while executing Encapsulation in Python. They are:

  • Public Members
  • Private Members
  • Protected Members

Public Members

Members of the public can be accessed from anywhere from a class. By default, all of the class variables are public.

# create a class say employDetails
class employDetails:

    # Create a __init_ constructor which accepts employName and employId as arguments 
    def __init__(self, employName, employId):
        # create public data members
        self.employName = employName;
        self.employId = employId;

    # Create a function say displayEmployId which prints 
    # the employ id when it is called
    def displayEmployId(self): 
        # Access the public data member of the class and print the result
        print("employId: ", self.employId)

# create an object of the class employDetails
employdetails_obj = employDetails("John", 2122);

# Access the public data member of the class and print the result
print("employName: ", employdetails_obj.employName)  

# call the public member function displayEmployId of the class employDetails
employdetails_obj.displayEmployId()

Output:

employName: John
employId: 2122

The variable employName and employId are both public in class employDetails. These data members are available throughout the program.

Private Members

Private members are accessible within the class. To define a private member, use a double underscore “__” before the member name.

Private members and protected members are the same thing. The difference is that private class members should not be accessed by anyone outside the class or its base classes. Private instance variable variables that can be accessed outside of a class do not exist in Python.

Python’s private and secured members can be accessed from outside the class by renaming them.

# create a class say employDetails
class employDetails:
   
   # Create a __init_ constructor which accepts employName and employId as arguments 
   def __init__(self, employName, employId):
      # Create a public variable
      self.employName = employName
      # Create private variable prefixed with "__"
      self.__employId = employId

# create an object of the class employDetails and call it
employdetails_obj = employDetails("John", 2122)

# Access the public variable name of the class and print the result
print("employName:",employdetails_obj.employName)

# Access the private data variable __employId of the class employDetails and print the result
print("employId:",employdetails_obj._employDetails__employId)

Output:

employName: John
employId: 2122

__employId is a private variable in class employDetails; thus, it is accessed by creating an object/instance.

Protected Members

Protected members can be accessed both within the class and by its subclasses. To define a protected member, use a single underscore “_” before the member name.

The protected variable can be accessed from the class and in derived classes (it can even be updated in derived classes), but it is not usually accessed outside of the class body.

The __init__ method(constructor), runs when an object of a type is instantiated.

# create a class say employDetails
class employDetails:
    # Creat which accepts employName and employId as arguments  
    def __init__(self, employName, employId):
        # protected data members as they are prefixed with single underscore "_"
        self._employName = employName
        self._employId = employId

# create object of the class employDetails and call it 
employdetails_obj = employDetails("John", 2122)

# Access the protected members of the class and print the result
print("employName:",employdetails_obj._employName)
print("employId:",employdetails_obj._employId)

Output:

employName: John
employId: 2122

Abstraction

Abstraction hides the unnecessary code/internal details and shows only functionalities. Also, when we do not want to reveal sensitive parts of our code implementation, data abstraction comes into play.

Data abstraction in Python is accomplished by creating abstract classes.

Real-time example

Assume you purchased a movie ticket from BookMyShow via net banking or another method. You have no idea how the pin is generated or how the verification is carried out. This is known as ‘abstraction’ in programming, and it basically means that you only show the implementation details of a specific process and hide the details from the user. It is used to simplify complex problems by modeling problem-specific classes.

 

Comments in Python

Comments are descriptions that help programmers better understand the program’s intent and functionality.

The Python interpreter completely ignores them.

  • Python code can be explained using comments.
  • Comments can be used to improve the readability of the code.
  • When testing code, comments can be used to prevent execution.

Advantages of Comments 

The use of comments in programs improves the readability of our code. It improves the readability of the program and helps us remember why certain blocks of code were written.

Aside from that, comments can be used to ignore certain code while testing other blocks of code. This provides a simple way to prevent the execution of certain lines or to quickly write pseudo-code for the program.

Python comments are classified into three types:

  • Single line Comments
  • Multiline Comments
  • Docstring Comments

Single line Comments

Single-line comments in Python have proven to be useful for providing concise descriptions of parameters, function definitions, and expressions.

To write a single-line comment in Python, use the hash symbol (#) with no white space and continues until the end of the line. If the comment continues to the next line, add a hashtag and resume the conversation.

Example1

# Print the string
print("Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms")

Output:

Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms

Explanation

Here the "Print the string" is the comment. 
The Python interpreter ignores this line.

Everything following # is ignored. As a result, we can write the above program in a single line as shown below:

Example2

print("Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms") # Print the string

Output:

Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms

Explanation

Here it will produce the same results as Example1. 
All the text following (#) is ignored by the interpreter.

Multiline Comments

Multiline comments are not supported in Python. However, there are other methods for writing multiline comments.

  • Writing multiline comments using Multiple Hashtags (#)
  • Writing multiline comments using String Literals

Writing multiline comments using Multiple Hashtags (#):

In Python, we can use multiple hashtags (#) to write multiline comments. Every line will be treated as a single-line comment.

# This is an example for writting multiline comments
# in python using multiple hashtags(#)
print("Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms")

Output:

Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms

Writing multiline comments using String Literals:

Python ignores string literals that are not assigned to a variable, so we can use them as comments.

Example1

# Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms
'Writing multiline comments using String Literals'

Explanation

The second line of the code is a string, but it is not assigned to any
variable or function. As a result, the interpreter ignores the string.

Similarly, we can write multiline comments using multiline strings (triple quotes).

( ‘ )or ( ” ) symbols can be used as the quotation character.

Example2

'''

This is an example for writting multiline comments
in python using string literals

'''
print("Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms")

Output:

Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms

Explanation

The interpreter ignores the multiline string because it is not 
assigned to any variable. It is technically not a multiline comment, 
but it can be used as one.

Python Docstring

Python docstrings are the strings enclosed in triple quotes that appear immediately after the defined function. It’s intended to link documentation created for Python modules, methods, classes, and functions. It is placed immediately beneath the function, module, or class to explain what they do. Using the __doc__ attribute, the docstring is then easily accessible in Python.

A documentation string is a string literal used as the first lines of a code block, such as a function.

A documentation string, unlike a regular comment, can be accessed at runtime via the obj.__doc__ attribute, where obj is the name of the function.

Typically, a documentation string is used to generate code documentation automatically.

Docstrings are documentation strings.

Docstrings are not, strictly speaking, comments. They define anonymous variables that contain references to the strings. They are also not ignored by the Python interpreter.

Python has two types of docstrings:

  • One-line docstrings
  • Multi-line docstrings

One-line docstrings:

A one-line docstring, as the name implies, fits one line. A one-line docstring starts with triple quotes (“””) and ends with triple quotes (“””). There will also be no blank lines before or after the one-line docstring.

Example

def add(x, y):
    """Here it adds the x, y values and print the result"""
    return x+y


# Print the docstring of the above declared add() function 
print(add.__doc__)

Output:

Here it adds the x, y values and print the result

Multi-line docstrings:

A multi-line docstring, as compared to a one-line docstring, can span multiple lines. A multi-line docstring also begins with triple quotes (“””) and ends with triple quotes (“””).

Example

def add(x, y):
    """ Here we are writing the 
        multiline docstrings
        by writing the function that accepts 2 variables
        as arguments      
    """

How Can We Write More Effective Comments?

  • Use comments to describe what a function does rather than the specifics of how it does it.
  • Remove as many redundant comments as you can. Try writing code that can explain itself by using more descriptive function/variable names.
  • Make your comments as brief and concise as possible.