Python remove from list by value – Python: Remove Elements from List by Value

Python remove from list by value: Lists are ordered sequences that can contain a wide range of object types. Members on lists can also be duplicated. Lists in Python are equivalent to arrays in other programming languages. There is, however, one significant difference. Arrays can only have elements of the same data type, whereas Python lists can have items of different data types.

Python Lists have several methods for removing elements from the list.

Examples:

Input:

givenlist=["hello", "this", "is", "Btech", "Geeks" ,"is" ] , value=is

Output:

["hello", "this", "Btech", "Geeks"]

Remove Elements from the List by Values

Python list remove element by value: There are several ways to remove elements from the list by values some of them are:

Method #1:Using remove() function

Python remove element from list by value: The remove method removes a list element based on its value rather than its index. When more than one element matches the provided value, the first matching element (the one with the lowest index) is removed. This is useful when you know which element needs to be removed ahead of time and don’t want to waste time looking for its index before removing it.

Let us now use the remove() function to remove the first instance of an element ‘is’.

Below is the implementation:

# Function which removes the element for given value and returns list
def removeValue(givenlist, value):
    # removing the value using remove()
    givenlist.remove(value)
    # return the list
    return givenlist

# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks", "is"]
# given value which is to be removed
value = 'is'
# passing list and value to removeValue function to remove the element
print(removeValue(givenlist, value))

Output:

['hello', 'this', 'Btech', 'Geeks', 'is']

If we use the remove() function to remove an element from a list that does not exist, what happens? In that case, Value Error will be returned.

Method #2: Removing given value using remove() if exist

Python remove item from list by value: To avoid the ValueError, we check to see if the value is already in the list and then remove it.

Below is the implementation:

# Function which removes the element for given value and returns list
def removeValue(givenlist, value):
  # checking if value is present in givenlist
    if value in givenlist:
     # removing the value using remove()
        givenlist.remove(value)
    # return the list
    return givenlist

# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks", "is"]
# given value which is to be removed
value = 'is'
# passing list and value to removeValue function to remove the element
print(removeValue(givenlist, value))

Output:

['hello', 'this', 'Btech', 'Geeks', 'is']

Method #3:Removing all occurrences of  given value

Python remove value from list: As we saw in the previous examples, the remove() function always deletes the first occurrence of the given element from the list. To delete all occurrences of an element, we must use the remove() function in a loop until all occurrences are gone.

So we use while loop to achieve that.

Below is the implementation:

# Function which removes the element for given value and returns list
def removeValue(givenlist, value):
    # using while loop to remove all occurrences of given value
    while(value in givenlist):
        # removing the value using remove()
        givenlist.remove(value)
       # return the list
    return givenlist

# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks", "is"]
# given value which is to be removed
value = 'is'
# passing list and value to removeValue function to remove the element
print(removeValue(givenlist, value))

Output:

['hello', 'this', 'Btech', 'Geeks']

Method #4: Using values, remove all occurrences of multiple elements from a list.

Remove item from list python by value: Assume we have a list of numbers and another list of values that we want to remove from the first list. We want to remove all of the elements from list2 from list1.

We’ve created a separate function for this, which takes two different lists as arguments.

  • The first is the givenlist.
  • The elements we want to remove are listed in the second list(valuelist)

It deletes all occurrences from the original list for each element in the second list.

Approach:

  • Traverse the value list
  • Using while loop remove all occurrences of the value from given list.
  • Return given list

Below is the implementation:

# Function which removes the element for given value and returns list
def removeValue(givenlist, valuelist):
    # Traverse the value list
    for value in valuelist:
       # using while loop to remove all occurrences of given value
        while(value in givenlist):
            # removing the value using remove()
            givenlist.remove(value)
           # return the list
    return givenlist

# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks", "is"]
# given value list which is to be removed
valuelist = ['is', 'hello', 'this']
# passing list and valuelist to removeValue function to remove the element
print(removeValue(givenlist, valuelist))

Output:

['Btech', 'Geeks']

Related Programs:

Python access string by index – Python : How to access characters in string by index ?

How to access characters in string by index

A string is a collection of characters.

Python access string by index: A character is simply a representation of something. The English language, for example, has 26 characters.
Computers work with numbers rather than characters (binary). Despite the fact that you see characters on your screen, they are stored and manipulated internally as a series of 0s and 1s.
The process of converting a character to a number is known as encoding, and the process of converting a number to a character is known as decoding. Two of the most common encodings are ASCII and Unicode.
A string in Python is a sequence of Unicode characters. Unicode was created in order to include every character in every language and to bring encoding uniformity. Python Unicode is capable of teaching you everything you need to know about Unicode.

Examples:

Input:

string="Hello this is BTechGeeks" index=3

Output:

l

Retrieve characters in string by index

Python char at index: In this article, we will look at how to access characters in a string using an index.

>1)Accessing characters in a string by index | indexof

Python uses a zero-based indexing system for strings: the first character has index 0, the next has index 1, and so on.

The length of the string – 1 will be the index of the last character.

Suppose we want to access 3rd index in input string

We can implement it as:

# Given string
string = "Hello this is BtechGeeks"
# Given index
index = 3
character = string[index]
# printing the character at given index
print(character)

Output:

l

>2)Using a negative index to access string elements

Negative numbers may be used to specify string indices, in which case indexing is performed from the beginning of the string backward:

The last character is represented by string[-1]

The second-to-last character by string[-2], and so on.

If the length of the string is n, string[-n] returns the first character of the string.

Below is the implementation:

# Given string
string = "Hello this is BtechGeeks"
# given index from end
index = 3
# printing last two characters of string
print("Last character in the given string : ", string[-1])
print("Second Last character in given string : ", string[-2])
# printing n th character from end
print(str(index)+" character from end in given string :", string[-index])

Output:

Last character in the given string :  s
Second Last character in given string :  k
3 character from end in given string : e

>3)Using String Slicing :

# Given string
string = "Hello this is BtechGeeks"
# given start index and end index
startindex = 14
endindex = 19
# using slicing
print(string[startindex:endindex])

Output:

Btech

>4)Accessing Out Of range character in given string using Exceptional Handling:

IndexError will be thrown if an element in a string is accessed that is outside of its range, i.e. greater than its length. As a result, we should always check the size of an element before accessing it by index, i.e.

To handle the error we use exceptional handling in python

Below is the implementation:

# Given string
string = "Hello this is BtechGeeks"
# given index
index = 50
# using try and except
try:
    # if the given index is less than string length then it will print
    print(string[index])
# if index is out of range then it will print out of range
except:
    print("Index out of range")

Output:

Index out of range

 

Related Programs:

Numpy e^x – Python NumPy expm1() Function

Python NumPy expm1() Function

NumPy expm1() Function:

Numpy e^x: The expm1() function of the NumPy module calculates the ex-1, which is e raised to the power of a given number minus 1. Here, e is the natural logarithm’s base, and its value is about 2.718282.

Syntax:

numpy.expm1(a, out=None)

Parameters

a: This is required. It is the array or an object given as input.

out: This is optional. It is the location where the result will be stored. It must have a shape that the inputs broadcast to if it is provided. If None or not given, a newly allocated array is returned.

Return Value: 

The exponential minus 1( ex-1) value of each element of the given array(a) is returned by the expm1() function of the NumPy module.

NumPy expm1() Function in Python

Example1

Approach:

  • Import numpy module using the import keyword
  • Pass some random list as an argument to the array() function of the numpy module to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Pass the above-given array as an argument to the expm1() function of the numpy module to get the exponential minus 1 (ex-1) values of each element of the given array.
  • Store it in another variable.
  • Print the exponential minus 1 (ex-1) values of each element of the given array
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function 
# of the Numpy module to create an array. 
# Store it in a variable.
gvn_arry = np.array([3, 6, 4, 10, 1])                     
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
print()
# Pass the above given array as an argument to the expm1() function of the 
# numpy module to get the exponential minus 1 (e^x-1) values of each element of 
# the given array
# Store it in another variable.
rslt = np.expm1(gvn_arry)
# Print the exponential minus 1 (e^x-1) values of each element of the given array
print("The exponential minus 1 (e^x-1) values of each element of the given array:")
print(rslt)

Output:

The above given array is:
[ 3 6 4 10 1]

The exponential minus 1 (e^x-1) values of each element of the given array:
[1.90855369e+01 4.02428793e+02 5.35981500e+01 2.20254658e+04
1.71828183e+00]

Example2(Plotting a Graph)

Approach:

  • Import numpy module using the import keyword
  • Import pyplot from the matplotlib module using the import keyword
  • Give some random list as static input and store it in a variable.
  • Pass the above-given list as an argument to the expm1() function of the numpy module to get the exponential minus 1 (e^x-1) values of each element of the given array.
  • Store it in another variable.
  • Store the above input array in another variable for plotting the input array vs input array.
  • Plot the input array versus input array with some random color and marker values using the plot() function of the matplotlib module
  • Plot the output array(e^x-1) versus input array with some other random color and marker values using the plot function of the matplotlib module
  • Give the title of the plot using the title() function of the matplotlib module
  • Display the plot using the show() function of the matplotlib module.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Import pyplot from the matplotlib module using the import keyword
import matplotlib.pyplot as plt
# Give some random list as static input and store it in a variable. 
gvn_arry = [1.3, 1, 2.4, 3.2, 4]
# Pass the above-given list as an argument to the expm1() function of the numpy module to 
# get the exponential minus 1 (e^x-1) values of each element of the given array.
# Store it in another variable.
rslt_arry = np.expm1(gvn_arry)
# Store the above input array in another variable for plotting the input array vs input array.
temp_inputarry = [1.3, 1, 2.4, 3.2, 4]
# Plot the input array versus input array with some random color and marker values using
# the plot() function of the matplotlib module
plt.plot(gvn_arry, temp_inputarry, color = 'green', marker = "*")
# Plot the output array(e^x-1) versus input array with some other random color 
# and marker values using the plot function of the matplotlib module
plt.plot(rslt_arry, temp_inputarry, color = 'orange', marker = "o")
# Give the title of the plot using the title() function of the matplotlib module
plt.title("Plotting Exponential minus 1 (e^x-1) values:")
plt.xlabel("X")
plt.ylabel("Y")
# Display the plot using the show() function of the matplotlib module.
plt.show()

Output:

Plotting Exponential minus 1(e^x-1) Values

How to multiply two matrices in python – Python Program for Multiplication of Two Matrices | How do you do Matrix Multiplication in Python?

Program for Multiplication of Two Matrices in Python and C++ Programming

How to multiply two matrices in python: Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Looking across the web for guidance on Multiplication of Two Matrices in Python? Before you begin your learning on Matrix Multiplication of Two Matrices know what is meant by a Matrix and what does Matrix Multiplication in actual means. This tutorial is going to be extremely helpful for you as it assists you completely on How to Multiply Two Matrices in Python using different methods like nested loops, nested list comprehension, etc. Furthermore, we have written simple python programs for multiplying two matrices clearly.

What is a Matrix?

Matrix multiplication python: A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

What is Matrix Multiplication?

How to do matrix multiplication in python: Matrix multiplication is only possible if the second matrix’s column equals the first matrix’s rows. A matrix can be represented in Python as a nested list ( a list inside a list ).

Examples for Matrix Multiplication:

Example 1:

Input:

Matrix 1  =  [  1  -8    7  ]
                    [  0   2    5  ]
                    [  1   6    2 ]
                      
Matrix 2 =   [   5    2   -6  ]
                    [   1    8    9 ]
                    [   3    5    7 ]

Output:

printing the matrix A :
1 -8 7
0 2 5
1 6 2
printing the matrix B :
5 2 -6
1 8 9
3 5 7
Printing the product of matrices : 
18 -27 -29
17 41 53
17 60 62

Example 2:

Input:

Matrix 1  =  1 2 3 
                  -5 8 7 
                   6 4 5 
                      
Matrix 2 =  2 7 9 
                  0 -8 5 
                  6 -5 2

Output:

Enter the number of rows and columns of the first matrix3
3
Enter the number of rows and columns of the second matrix3
3
Enter element A11 = 1
Enter element A12 = 2
Enter element A13 = 3
Enter element A21 = -5
Enter element A22 = 8
Enter element A23 = 7
Enter element A31 = 6
Enter element A32 = 4
Enter element A33 = 5

Enter elements of 2nd matrix: 
Enter element B11 = 2
Enter element B12 = 7
Enter element B13 = 9
Enter element B21 = 0
Enter element B22 = -8
Enter element B23 = 5
Enter element B31 = 6
Enter element B32 = -5
Enter element B33 = 2

printing the matrix A
1 2 3 
-5 8 7 
6 4 5

printing the matrix B
2 7 9 
0 -8 5 
6 -5 2 
Print the product of two matrices A and B
20 -24 25 
32 -134 9 
42 -15 84

Given two matrices, the task is to write a program in Python and C++ to multiply the two matrices.

Simple Python Program for Matrix Multiplication

Method #1: Using Nested Loops in Python

A matrix can be implemented as a nested list in Python (list inside a list).

Each element can be thought of as a row in the matrix.

X[0] can be used to choose the first row. Furthermore, the element in the first row, the first column can be chosen as X[0][0].

The multiplication of two matrices X and Y is defined if the number of columns in X equals the number of rows in Y.

Here we give the matrix input as static.

XY is defined and has the dimension n x l if X is a n x m matrix and Y is a m x l matrix (but YX is not defined). In Python, there are a few different approaches to implement matrix multiplication.

Below is the  implementation:

# given matrix A
A = [[1, - 8, 7],
     [0, 2, 5],
     [1, 6, 2]]
# given matrix B
B = [[5, 2, - 6],
     [1, 8, 9],
     [3, 5, 7]]
# Initialize the product of matrices elements to 0
matrixProduct = [[0, 0, 0],
                 [0, 0, 0],
                 [0, 0, 0]]
# Traverse the rows of A
for i in range(len(A)):
    #  Traverse the  columns of B
    for j in range(len(B[0])):
        # Traverse the  rows of B
        for k in range(len(B)):
            matrixProduct[i][j] += A[i][k] * B[k][j]
# printing the matrix A
print("printing the matrix A :")
for rows in A:
    print(*rows)
# printing the matrix B
print("printing the matrix B :")
for rows in B:
    print(*rows)
# printing the product of matrices
print("Printing the product of matrices : ")
for rows in matrixProduct:
    print(*rows)

Python Program for Matrix Multiplication using Nested Loops

Output:

printing the matrix A :
1 -8 7
0 2 5
1 6 2
printing the matrix B :
5 2 -6
1 8 9
3 5 7
Printing the product of matrices : 
18 -27 -29
17 41 53
17 60 62

Explanation:

To go through each row and column in our program, we used nested for loops. In the end, we add up the sum of the items.

This technique is simple, but it becomes computationally expensive as the order of the matrix increases.

We recommend NumPy for larger matrix operations because it is several (in the order of 1000) times faster than the above code.

Method #2: Matrix Multiplication List Comprehension Python

This program produces the same results as the previous one. To understand the preceding code, we must first know the built-in method zip() and how to unpack an argument list with the * operator.

To loop through each element in the matrix, we utilized nested list comprehension. At first glance, the code appears to be complicated and difficult to understand. However, once you’ve learned list comprehensions, you won’t want to go back to nested loops.

Below is the implementation:

# given matrix A
A = [[1, - 8, 7],
     [0, 2, 5],
     [1, 6, 2]]
# given matrix B
B = [[5, 2, - 6],
     [1, 8, 9],
     [3, 5, 7]]
# using list comprehension to do product of matrices
matrixProduct = [[sum(a*b for a, b in zip(row, col))
                  for col in zip(*B)] for row in A]

# printing the matrix A
print("printing the matrix A :")
for rows in A:
    print(*rows)
# printing the matrix B
print("printing the matrix B :")
for rows in B:
    print(*rows)
# printing the product of matrices
print("Printing the product of matrices : ")
for rows in matrixProduct:
    print(*rows)

Python Program for Matrix Multiplication using List Comprehension

Output:

printing the matrix A :
1 -8 7
0 2 5
1 6 2
printing the matrix B :
5 2 -6
1 8 9
3 5 7
Printing the product of matrices : 
18 -27 -29
17 41 53
17 60 62

Method #3: Using Nested Loops in C++

We used nesting loops in this program to iterate through and row and column. In order to multiply two matrices, we will do the multiplication of matrices as below

Let us take dynamic input in this case.

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{
    int A[100][100], B[100][100], product[100][100], row1,
        col1, row2, col2, i, j, k;

    cout << "Enter the number of rows and columns of the "
            "first matrix";
    cin >> row1 >> col1;
    cout << "Enter the number of rows and columns of the "
            "second matrix";
    cin >> row2 >> col2;

    // Initializing matrix A with the user defined values
    for (i = 0; i < row1; ++i)
        for (j = 0; j < col1; ++j) {
            cout << "Enter element A" << i + 1 << j + 1
                 << " = ";
            cin >> A[i][j];
        }
    // Initializing matrix B with the user defined values
    cout << endl
         << "Enter elements of 2nd matrix: " << endl;
    for (i = 0; i < row2; ++i)
        for (j = 0; j < col2; ++j) {
            cout << "Enter element B" << i + 1 << j + 1
                 << " = ";
            cin >> B[i][j];
        }

    // Initializing the resultant product matrix with 0 to
    // all elements
    for (i = 0; i < row1; ++i)
        for (j = 0; j < col2; ++j) {
            product[i][j] = 0;
        }

    // Calculating the product of two matrices A and B
    for (i = 0; i < row1; ++i)
        for (j = 0; j < col2; ++j)
            for (k = 0; k < col1; ++k) {
                product[i][j] += A[i][k] * B[k][j];
            }
    // printing matrix A
    cout << endl << " printing the matrix A" << endl;
    for (i = 0; i < row1; ++i) {
        for (j = 0; j < col1; ++j) {
            cout << A[i][j] << "  ";
        }
        cout << endl;
    }
    // printing matrix B
    cout << endl << " printing the matrix B" << endl;
    for (i = 0; i < row2; ++i) {
        for (j = 0; j < col2; ++j) {
            cout << B[i][j] << "  ";
        }
        cout << endl;
    }

    // Print the product of two matrices A and B
    cout << "Print the product of two matrices A and B"
         << endl;
    for (i = 0; i < row1; ++i) {
        for (j = 0; j < col2; ++j) {
            cout << product[i][j] << "  ";
        }
        cout << endl;
    }

    return 0;
}

Output:

Enter the number of rows and columns of the first matrix3
3
Enter the number of rows and columns of the second matrix3
3
Enter element A11 = 1
Enter element A12 = 2
Enter element A13 = 3
Enter element A21 = -5
Enter element A22 = 8
Enter element A23 = 7
Enter element A31 = 6
Enter element A32 = 4
Enter element A33 = 5

Enter elements of 2nd matrix: 
Enter element B11 = 2
Enter element B12 = 7
Enter element B13 = 9
Enter element B21 = 0
Enter element B22 = -8
Enter element B23 = 5
Enter element B31 = 6
Enter element B32 = -5
Enter element B33 = 2

printing the matrix A
1 2 3 
-5 8 7 
6 4 5

printing the matrix B
2 7 9 
0 -8 5 
6 -5 2 
Print the product of two matrices A and B
20 -24 25 
32 -134 9 
42 -15 84

How to Multiply Two Matrices in Python using Numpy?

import numpy as np

C = np.array([[3, 6, 7], [5, -3, 0]])
D = np.array([[1, 1], [2, 1], [3, -3]])
E = C.dot(D)
print(E)

''' 

Output:

[[ 36 -12]
[ -1 2]]

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Related Programs:

Python print precision – Program to Handle Precision Values in Python

Program to Handle Precision Values

Python print precision: Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Python treats every number with a decimal point as a double precision floating point number by default. The Decimal is a form of floating decimal point with more precision and a narrower range than the float. It is ideal for monetary and financial calculations. It is also more similar to how humans operate with numbers.

In contrast to hardware-based binary floating point, the decimal module features user-adjustable precision that can be as large as required for a given situation. The precision is set to 28 places by default.

Some values cannot be represented exactly in a float data format. For example, saving the 0.1 value in the float (binary floating point value) variable gives just an approximation of the value. Similarly, the 1/5 number cannot be precisely expressed in decimal floating point format.
Neither type is ideal in general, decimal types are better suited for financial and monetary computations, while double/float types are better suited for scientific calculations.

Handling precision values in Python:

We frequently encounter circumstances in which we process integer or numeric data into any application or manipulation procedures, regardless of programming language. We find data with decimal values using the same procedure. This is when we must deal with accuracy values.

Python has a number of functions for dealing with accuracy values for numeric data. It allows us to exclude decimal points or have customized values based on the position of the decimal values in the number.

Examples:

Example1:

Input:

given_number = 2345.1347216482926    precisionlimit=4

Output:

the given number upto 4 decimal places 2345.1347

Example2:

Input:

given_number = 2345.13    precisionlimit=4

Output:

the given number upto 4 decimal places 2345.1300

Code for Handling Precision Values in Python

There are several ways to handle the precision values in python some of them are:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1:Using % operator

We may format the number as well as specify precision boundaries with the ‘ % ‘ operator. This allows us to customize the precise point restrictions that are included in the final number.

Syntax:

'%.point'%number

Parameters:

point: It denotes the number of points we want after the decimal in the integer.
number : The integer value to be worked on is represented by the number.

Below is the implementation:

# given number
given_number = 2345.1347216482926
# using % operator and printing upto 4 decimal places
ans = '%.4f' % given_number
# print the answer
print("the given number upto 4 decimal places", ans)

Output:

the given number upto 4 decimal places 2345.1347

Method #2:Using format function

We can use the format() function to set limits for precision values, just like we can with the percent operator. We format the data as a string and set the limits for the points to be included after the decimal portion of the number with the format() function.

Syntax:

print ("{0:.pointf}".format(number))

Below is the implementation:

# given number
given_number = 2345.1336327777377
# using % operator and printing upto 5 decimal places
ans = '{0:.5f}' .format(given_number)
# print the answer
print("the given number upto 5 decimal places", ans)

Output:

the given number upto 5 decimal places 2345.13363

Method #3:Using round() function

We can extract and display integer values in a customized format using the Python round() function. As a check for precision handling, we can select the number of digits to be displayed after the decimal point.

Syntax:

round(number, point)

Below is the implementation:

# given number
given_number = 2345.1336327777377
# using % operator and printing upto 4 decimal places
ans = round(given_number, 5)
# print the answer
print("the given number upto 5 decimal places", ans)

Output:

the given number upto 5 decimal places 2345.13363

4)Math functions in Python to handle precision values

Aside from the functions listed above, Python also provides us with a math module that contains a set of functions for dealing with precision values.

The Python math module includes the following functions for dealing with precision values–

1)trunc() function
2)The ceil() and floor() functions in Python
Let us go over them one by one.

Method #4:Using trunc() function

The trunc() function terminates all digits after the decimal points. That is, it only returns the digits preceding the decimal point.

Syntax:

import math
math.trunc(given number)

Below is the implementation:

import math
# given number
given_number = 39245.1336327777377
# truncating all the digits of given number
truncnumber = math.trunc(given_number)
# print the answer
print("the given number after truncating digits", truncnumber)

Output:

the given number after truncating digits 39245

Method #5:Using ceil() and floor() functions

We can round off decimal numbers to the nearest high or low value using the ceil() and floor() functions.

The ceil() function takes the decimal number and rounds it up to the next large number after it. The floor() function, on the other hand, rounds the value to the next lowest value before it.

Below is the implementation:

import math
given_number = 3246.3421

# prining the ceil value of the given number
print('printing ceil value of the given numnber',
      given_number, '=', math.ceil(given_number))

# prining the floor value of the given number
print('printing floor value of the given numnber',
      given_number, '=', math.floor(given_number))

Output:

printing ceil value of the given numnber 3246.3421 = 3247
printing floor value of the given numnber 3246.3421 = 3246

Related Programs:

Python divisor – Python Program to Find the Smallest Divisor of an Integer

Program to Find the Smallest Divisor of an Integer

Python divisor: Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Given a number, the task is to find the smallest number which divides the given number in Python.

Examples:

Example1:

Input:

given number = 91

Output:

The smallest which divides the given number [ 91 ] = 7

Example2:

Input:

given number = 169

Output:

Enter some random number = 169
The smallest which divides the given number [ 169 ] = 13

Program to Find the Smallest Divisor of an Integer in Python

Divisor python: There are several ways to find the smallest divisor of the given number in Python some of them are:

Method #1:Using for loop(Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Loop from 2 to given number using For loop.
  • Check if the iterator value divides the given number perfectly using the if statement and modulus operator.
  • Print the iterator value.
  • Break the loop using the break statement.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvnNumb = 91
# Loop from 2 to given number using For loop.
for itervalue in range(2, gvnNumb+1):
    # Check if the iterator value divides the given number
    # perfectly using the if statement and modulus operator.
    if(gvnNumb % itervalue == 0):
        # Print the iterator value.

        print(
            'The smallest which divides the given number [', gvnNumb, '] =', itervalue)
        # Break the loop using the break statement.
        break

Output:

The smallest which divides the given number [ 91 ] = 7

Method #2: Using for loop(User Input )

Approach:

  • Give the number as user input using the int(input()) function that converts the string to an integer.
  • Store it in a variable.
  • Loop from 2 to given number using For loop.
  • Check if the iterator value divides the given number perfectly using the if statement and modulus operator.
  • Print the iterator value.
  • Break the loop using the break statement.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function that converts
# the string to an integer.
# Store it in a variable.
gvnNumb = int(input('Enter some random number = '))
# Loop from 2 to given number using For loop.
for itervalue in range(2, gvnNumb+1):
    # Check if the iterator value divides the given number
    # perfectly using the if statement and modulus operator.
    if(gvnNumb % itervalue == 0):
        # Print the iterator value.

        print(
            'The smallest which divides the given number [', gvnNumb, '] =', itervalue)
        # Break the loop using the break statement.
        break

Output:

Enter some random number = 369
The smallest which divides the given number [ 369 ] = 3

Explanation:

  • The user must enter a number.
  • The for loop has a range of 2 to the number
  • If the remainder of the number is zero when divided by the value of i the element is a divisor of the number.
  • Print the number and break the loop.

Method #3:Using While Loop(Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take a temporary variable and initialize it with 2.
  • Loop till the temporary variable is less than or equal to the given number using the while loop.
  • Check if the temporary variable divides the given number perfectly using the if statement and modulus operator.
  • Print the temporary variable.
  • Break the loop using the break statement.
  • Increase the value of the temporary variable by 1.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvnNumb = 125
# Take a temporary variable and initialize it with 2.
tempnumber = 2
# Loop till the temporary variable is less than
# or equal to the given number using the while loop.
while(tempnumber <= gvnNumb):
    # Check if the temporary variable divides the given number perfectly
    # using the if statement and modulus operator.
    if(gvnNumb % tempnumber == 0):
        # Print the iterator value.
        print(
            'The smallest which divides the given number [', gvnNumb, '] =', tempnumber)
        # Break the loop using the break statement.
        break
 # Increase the value of the temporary variable by 1.
    tempnumber = tempnumber+1

Output:

The smallest which divides the given number [ 125 ] = 5

Method #4:Using While Loop(User Input)

Approach:

  • Give the number as user input using the int(input()) function that converts the string to an integer.
  • Store it in a variable.
  • Take a temporary variable and initialize it with 2.
  • Loop till the temporary variable is less than or equal to the given number using the while loop.
  • Check if the temporary variable divides the given number perfectly using the if statement and modulus operator.
  • Print the temporary variable.
  • Break the loop using the break statement.
  • Increase the value of the temporary variable by 1.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function that converts
# the string to an integer.
# Store it in a variable.
gvnNumb = int(input('Enter some random number = '))
# Take a temporary variable and initialize it with 2.
tempnumber = 2
# Loop till the temporary variable is less than
# or equal to the given number using the while loop.
while(tempnumber <= gvnNumb):
    # Check if the temporary variable divides the given number perfectly
    # using the if statement and modulus operator.
    if(gvnNumb % tempnumber == 0):
        # Print the iterator value.
        print(
            'The smallest which divides the given number [', gvnNumb, '] =', tempnumber)
        # Break the loop using the break statement.
        break
 # Increase the value of the temporary variable by 1.
    tempnumber = tempnumber+1

Output:

Enter some random number = 578
The smallest which divides the given number [ 578 ] = 2

Method #5:Using List Comprehension

Approach:

  • Give the number as user input using the int(input()) function that converts the string to an integer.
  • Store it in a variable.
  • Using List Comprehension, for loop and if statements add all the divisors of the given number from 2 to given number into the list.
  • Print the first element in the given list.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function that converts
# the string to an integer.
# Store it in a variable.
gvnNumb = int(input('Enter some random number = '))
# Using List Comprehension, for loop and if statements add
# all the divisors of the given number
# from 2 to given number into the list.
divList = [numbe for numbe in range(2, gvnNumb+1) if(gvnNumb % numbe == 0)]
smalldivi = divList[0]
# Print the first element in the given list.
print('The smallest which divides the given number [', gvnNumb, '] =', smalldivi)

Output:

Enter some random number = 169
The smallest which divides the given number [ 169 ] = 13

Related Programs:

Pandas drop by index – Python Pandas : How to drop rows in DataFrame by index labels

How to drop rows in DataFrame by index labels in Python ?

Pandas drop by index: In this article we are going to learn how to delete single or multiple rows from a Dataframe.

For this we are going to use the drop( ) function.

Syntax - DataFrame.drop( labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise' )

Where, the function accepts name/series of names in the label and deletes the rows or columns it points to. The axis is used to alter between rows and columns, 0 means rows and 1 means columns(default value is 0).

Also we have to pass inplace = True if we want the modified values to be updated in our dataframe object, as the drop( ) function returns the modified values into a new Dataframe object. To explain this properly we will be using inplace = True in all our programs.

We are going to use the following dataset as example

      Name          Age       Location       Country
a     Jill               16         Tokyo             Japan
b    Phoebe        38        New York        USA
c     Kirti             39         New York        USA
d     Veena         40         Delhi               India
e     John           54          Mumbai         India
f     Michael       21         Tokyo              Japan

Deleting a single Row in DataFrame by Row Index Label :

To delete a single row by the label we can just pass the label into the function.

Here let’s try to delete‘b’ row.

#program :

import numpy as np
import pandas as pd

#Examole data
students = [('Jill',   16,  'Tokyo',     'Japan'),
('Phoebe', 38,  'New York',  'USA'),
('Kirti',  39,  'New York',  'USA'),
('Veena',  40,  'Delhi',     'India'),
('John',   54,  'Mumbai',    'India'),
("Michael",21,  'Tokyo',     'Japan')]

#Creating an object of dataframe class
dfObj = pd.DataFrame(students, columns = ['Name' , 'Age', 'Location' , 'Country'], index=['a', 'b', 'c' , 'd' , 'e' , 'f'])
#Deleting 'b' row
dfObj.drop('b',inplace=True)
print(dfObj)

Output :

        Name     Age      Location       Country
a        Jill          16       Tokyo            Japan
c        Kirti        39       New York      USA
d      Veena      40       Delhi             India
e      John         54       Mumbai        India
f     Michael     21       Tokyo            Japan

Deleting Multiple Rows in DataFrame by Index Labels :

To delete multiple rows by their labels we can just pass the labels into the function inside a square bracket [ ].

Here let’s try to delete 'a' and 'b' row.

#program :

import numpy as np
import pandas as pd

#Examole data
students = [('Jill',   16,  'Tokyo',     'Japan'),
('Phoebe', 38,  'New York',  'USA'),
('Kirti',  39,  'New York',  'USA'),
('Veena',  40,  'Delhi',     'India'),
('John',   54,  'Mumbai',    'India'),
("Michael",21,  'Tokyo',     'Japan')]

#Creating an object of dataframe class
dfObj = pd.DataFrame(students, columns = ['Name' , 'Age', 'Location' , 'Country'], index=['a', 'b', 'c' , 'd' , 'e' , 'f'])

#Deleting 'a' and 'b' row
dfObj.drop(['a','b'],inplace=True)
print(dfObj)
Output :
      Name       Age     Location       Country
c     Kirti          39      New York      USA
d     Veena      40      Delhi             India
e     John         54     Mumbai         India
f     Michael     21     Tokyo             Japan

Deleting Multiple Rows by Index Position in DataFrame :

To delete multiple rows we know the index position, however, the function drop( ) doesn’t take indices as parameters. So we create the list of labels and pass them into the drop( ) function. Let’s try deleting the same rows again but by index.

#program :

import numpy as np
import pandas as pd

#Examole data
students = [('Jill',   16,  'Tokyo',     'Japan'),
('Phoebe', 38,  'New York',  'USA'),
('Kirti',  39,  'New York',  'USA'),
('Veena',  40,  'Delhi',     'India'),
('John',   54,  'Mumbai',    'India'),
("Michael",21,  'Tokyo',     'Japan')]

#Creating an object of dataframe class
dfObj = pd.DataFrame(students, columns = ['Name' , 'Age', 'Location' , 'Country'], index=['a', 'b', 'c' , 'd' , 'e' , 'f'])

#Deleting 1st and 2nd row
dfObj.drop([dfObj.index[0] , dfObj.index[1]],inplace=True)
print(dfObj)
Output :
      Name      Age     Location     Country
c     Kirti          39     New York     USA
d     Veena      40     Delhi            India
e     John         54    Mumbai        India
f     Michael     21     Tokyo          Japan

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Read more Articles on Python Data Analysis Using Padas – Remove Contents from a Dataframe

Semiperimeter area formula – Python Program to Calculate the Area, Semi Perimeter and Perimeter of a Triangle

Calculate the Area, Semi Perimeter and Perimeter of a Triangle

Semiperimeter area formula: Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

With an example, learn how to construct a Python program to find the Area of a Triangle, Perimeter of a Triangle, and Semi-Perimeter of a Triangle. Let’s look at the definitions and mathematics underlying Perimeter and Area of a Triangle before diving into the Python program to find Area of a Triangle.

Area of Triangle:

If we know the lengths of the three sides of a triangle, we can use Heron’s Formula to compute the area of the triangle.

Triangle Area = √((s*(s-a)*(s-b)*(s-c)))

Where

s = (a + b + c )/ 2

(Here s = semi perimeter and a, b, c are the three sides of a given_triangle)

Perimeter of a Triangle = a + b + c

Examples:

Example 1:

Input:

a = 24
b = 12
c = 22

Output:

The semiperimeter of the triangle with the sides 24 12 22 = 29.0
The perimeter of the triangle with the sides 24 12 22 = 58
The area of the triangle with the sides 24 12 22 =131.358

Example 2:

Input:

a = 5.6
b = 2.7
c = 7.9

Output:

The semiperimeter of the triangle with the sides 5.6 2.7 7.9 =8.100
The perimeter of the triangle with the sides 5.6 2.7 7.9 =16.200
The area of the triangle with the sides 5.6 2.7 7.9 =4.677

Program to Calculate the Area, Semi Perimeter and Perimeter of a Triangle

Let us calculate the area, semi perimeter and perimeter of Triangle in Python:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Calculating Semi Perimeter of the given triangle

We can calculate semi perimeter using the formula

s=(a+b+c)/2 where a , b ,c are sides of the triangle

Below is the implementation:

# given sides of the triangle
a = 24
b = 12
c = 22

# calculating the semi perimeter of the given triangle by using the formula
semi_perimeter = (a + b + c) / 2
# print semi_perimeter
print("The semiperimeter of the triangle with the sides", a, b, c, "=", semi_perimeter)

Output:

The semiperimeter of the triangle with the sides 24 12 22 = 29.0

2)Calculating Perimeter of the given triangle

We can calculate perimeter using the formula

perimeter=(a+b+c) where a , b ,c are sides of the triangle

Below is the implementation:

# given sides of the triangle
a = 24
b = 12
c = 22

# calculating the  perimeter of the given triangle by using the formula
perimetr = (a + b + c)
# print perimeter
print("The perimeter of the triangle with the sides", a, b, c, "=", perimetr)

Output:

The perimeter of the triangle with the sides 24 12 22 = 58

3)Calculating Area of Triangle

When three sides are specified in this program, the area of the triangle will be determined using Heron’s formula.

If you need to calculate the area of a triangle based on user input, you can utilize the input() function.

Approach:

  • Scan the sides of the given triangle.
  • The semi-perimeter will be calculated using Heron’s formula.
  • To determine the area of the triangle, use Area = (s*(s-a)*(s-b)*(s-c)) ** 0.5.
  • Finally, print the triangle’s area

Below is the implementation:

# given sides of the triangle
a = 24
b = 12
c = 22

# calculating the  semiperimeter of the given triangle by using the formula
s = (a + b + c)/2
# calculating area of triangle with given sides
triangleArea = (s*(s-a)*(s-b)*(s-c)) ** 0.5
# print the area of thee triangle
print("The area of the triangle with the sides",
      a, b, c, "=%0.3f" % triangleArea)

Output:

The area of the triangle with the sides 24 12 22 =131.358

Related Programs:

Get index of minimum python – Python Program to Find the Minimum Index of a Repeating Element in an Array/List

Program to Find the Minimum Index of a Repeating Element in an ArrayList

Get index of minimum python: Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Lists in Python:

Lists are one of Python’s most commonly used built-in data structures. You can make a list by putting all of the elements inside square brackets[ ] and separating them with commas. Lists can include any type of object, making them extremely useful and adaptable.

Given a list/array, the task is to find the minimum index of the repeating element in the given list in Python.

Examples:

Example1:

Input:

given list = [8, 12, 38, 7, 1, 9, 19, 11, 45, 62, 57, 18, 12, 32, 45, 7, 1]

Output:

The minimum index of the repeating element of the given list [8, 12, 38, 7, 1, 9, 19, 11, 45, 62, 57, 18, 12, 32, 45, 7, 1] :
 1

Example2:

Input:

given list =[7, 86, 23, 96, 11, 23, 45, 78, 96, 23, 79, 123, 456, 789]

Output:

The minimum index of the repeating element of the given list [7, 86, 23, 96, 11, 23, 45, 78, 96, 23, 79, 123, 456, 789] :
2

Program to Find the Minimum Index of a Repeating Element in an Array/List in Python

Below is the full approach for finding the minimum index of the repeating element in the given list in Python

1)Using Hashing with Counter() function(Static Input)

Counter() function:

The Counter class is a subset of the object data-set offered by Python3’s collections module. The Collections module provides the user with specialized container datatypes, acting as an alternative to Python’s general-purpose built-ins such as dictionaries, lists, and tuples.

The counter is a subclass that counts hashable objects. When called, it constructs an iterable hash table implicitly.

Approach:

  • Import the Counter function from the collections module.
  • Give the list as static input and store it in a variable.
  • Calculate the frequency of all the elements of the given list using the Counter() function and store it in a variable.
  • Traverse the given list using For loop.
  • Check if the element has a frequency greater than 1 using the if statement.
  • If it has a frequency greater than 1, then print the iterator value of the loop(which is the minimum index of the repeating element)
  • Break the loop using a break statement
  • The Exit of the Program.

Below is the implementation:

# Import the Counter function from the collections module.
from collections import Counter
# Give the list as static input and store it in a variable.
given_list = [8, 12, 38, 7, 1, 9, 19, 11, 45, 62, 57, 18, 12, 32, 45, 7, 1]
# Calculate the frequency of all the elements of the given list
# using the Counter() function and store it in a variable.
elemeFreq = Counter(given_list)
# Traverse the given list using For loop.
for indeval in range(len(given_list)):
    # Check if the element has a frequency greater than 1 using the if statement.
    if(elemeFreq[given_list[indeval]] > 1):
        # If it has a frequency greater than 1, then print the iterator value of the loop
        # (which is the minimum index of the repeating element)
        print('The minimum index of the repeating element of the given list',
              given_list, ':\n', indeval)
        # Break the loop using the break statement
        break

Output:

The minimum index of the repeating element of the given list [8, 12, 38, 7, 1, 9, 19, 11, 45, 62, 57, 18, 12, 32, 45, 7, 1] :
 1

Since we iterate only once the Time Complexity of the above approach is O(n).

2)Using Hashing with Counter() function(User Input)

Approach:

  • Import the Counter function from the collections module.
  • Give the list as user input using split(),int,map() and list() functions.
  • Store it in a variable.
  • Calculate the frequency of all the elements of the given list using the Counter() function and store it in a variable.
  • Traverse the given list using For loop.
  • Check if the element has a frequency greater than 1 using the if statement.
  • If it has a frequency greater than 1, then print the iterator value of the loop(which is the minimum index of the repeating element)
  • Break the loop using a break statement
  • The Exit of the Program.

Below is the implementation:

# Import the Counter function from the collections module.
from collections import Counter
# Give the list as user input using split(),int,map() and list() functions.
# Store it in a variable.
given_list = list(
    map(int, input('Enter some random list elements separated by spaces = ').split()))
# Calculate the frequency of all the elements of the given list
# using the Counter() function and store it in a variable.
elemeFreq = Counter(given_list)
# Traverse the given list using For loop.
for indeval in range(len(given_list)):
    # Check if the element has a frequency greater than 1 using the if statement.
    if(elemeFreq[given_list[indeval]] > 1):
        # If it has a frequency greater than 1, then print the iterator value of the loop
        # (which is the minimum index of the repeating element)
        print('The minimum index of the repeating element of the given list',
              given_list, ':\n', indeval)
        # Break the loop using break statement
        break

Output:

Enter some random list elements separated by spaces = 7 86 23 96 11 23 45 78 96 23 79 123 456 789
The minimum index of the repeating element of the given list [7, 86, 23, 96, 11, 23, 45, 78, 96, 23, 79, 123, 456, 789] :
2

Since we iterate only once the Time Complexity of the above approach is O(n).
Related Programs:

What is an evil number – Python Program to Check Evil Number or Not

Program to Check Evil Number or Not

What is an evil number: In the previous article, we have discussed Python Program to Determine Whether one String is a Rotation of Another
Evil Number :

The Evil number is another unique positive whole number with an even number of 1s in its binary representation.

example:

1) let n= 12

binary representation = 1100

# It has an even number of 1’s.  Therefore 12 is an evil number.

2) n= 4

binary representation = 100

It has an odd number of 1’s.  Therefore 4 is not an evil number.

Examples:

Example1:

Input:

Given Number = 6

Output:

The given number 6 is an Evil Number

Example2:

Input:

Given Number = 22

Output:

The given number 22 is Not an Evil Number

Program to Check Evil Number or Not

Below are the ways to check whether the given number is an evil number or not

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

Approach:

  • Give the number as static input and store it in a variable.
  • Convert the given number into a binary number using the bin() function and store it in another variable.
  • Take a variable say ‘c’ and initialize its value with zero.
  • Loop in the above obtained binary number using the for loop.
  • Check if the iterator value is equal to ‘1’ using the if conditional statement.
  • If the statement is true, increase the count value of the variable ‘c’ by 1 and store it in the same variable.
  • Check for the even number of  1’s by c %2 is equal to zero or not using the if conditional statement.
  • If the statement is true, print “The given number is an Evil Number”.
  • Else print “The given number is not an Evil Number”.
  • The Exit of the program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_num = 9
# Convert the given number into a binary number using the bin() function and
# store it in another variable.
k = bin(gvn_num)[2:]
# Take a variable say 'c' and initialize its value with zero.
c = 0
# Loop in the above obtained binary number using the for loop.
for i in k:
 # Check if the iterator value is equal to '1' using the if conditional statement.
    if(i == '1'):
     # If the statement is true, increase the count value of the variable 'c' by 1 and
        # store it in the same variable.
        c += 1
 # Check for the even number of  1's by c %2 is equal to zero or not using the
# if conditional statement.
if(c % 2 == 0):
  # If the statement is true, print "The given number is an Evil Number".
    print("The given number", gvn_num, "is an Evil Number")
else:
  # Else print "The given number is not an Evil Number".
    print("The given number", gvn_num, "is Not an Evil Number")

Output:

The given number 9 is an Evil Number

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

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Convert the given number into a binary number using the bin() function and store it in another variable.
  • Take a variable say ‘c’ and initialize its value with zero.
  • Loop in the above obtained binary number using the for loop.
  • Check if the iterator value is equal to ‘1’ using the if conditional statement.
  • If the statement is true, increase the count value of the variable ‘c’ by 1 and store it in the same variable.
  • Check for the even number of  1’s by c %2 is equal to zero or not using the if conditional statement.
  • If the statement is true, print “The given number is an Evil Number”.
  • Else print “The given number is not an Evil Number”.
  • The Exit of the program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
gvn_num = int(input("Enter some random number = "))
# Convert the given number into a binary number using the bin() function and
# store it in another variable.
k = bin(gvn_num)[2:]
# Take a variable say 'c' and initialize its value with zero.
c = 0
# Loop in the above obtained binary number using the for loop.
for i in k:
 # Check if the iterator value is equal to '1' using the if conditional statement.
    if(i == '1'):
     # If the statement is true, increase the count value of the variable 'c' by 1 and
        # store it in the same variable.
        c += 1
 # Check for the even number of  1's by c %2 is equal to zero or not using the
# if conditional statement.
if(c % 2 == 0):
  # If the statement is true, print "The given number is an Evil Number".
    print("The given number", gvn_num, "is an Evil Number")
else:
  # Else print "The given number is not an Evil Number".
    print("The given number", gvn_num, "is Not an Evil Number")

Output:

Enter some random number = 3
The given number 3 is an Evil Number

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.