Python

numpy.where() – Explained with examples

In this article, we will see various examples of numpy.where() function and how it works in python. For instance, like,

  • Using numpy.where() with single condition.
  • Using numpy.where() with multiple condition
  • Use numpy.where() to select indexes of elements that satisfy multiple conditions
  • Using numpy.where() without condition expression

In Python’s NumPy module, we can select elements with two different sequences based on conditions on the different array.

Syntax of np.where()

numpy.where(condition[, x, y])

Explanation:

  • The condition returns a NumPy array of bool.
  • X and Y are the arrays that are optional, which means either both are passed or not passed.
    • If it is passed then it returns the elements from x and y based on the condition depending on values in the bool array.
    • If x & y arguments are not passed and only condition argument is passed then it returns the indices of the elements that are True in bool numpy array.

Let’s dig in to see some examples.

Using numpy.where() with single condition

Let’s say we have two lists of the same size and a NumPy array.

arr = np.array([11, 12, 13, 14])
high_values = ['High', 'High', 'High', 'High']
low_values = ['Low', 'Low', 'Low', 'Low']

Now, we want to convert this numpy array to the array of the same size, where the values will be included from the list high_values and low_values. For instance, if the value in an array is less than 12, then replace it with the ‘low‘ and if the value in array arr is greater than 12 then replace it with the value ‘high‘.

So ultimately, the array will look like this:

['Low' 'Low' 'High' 'High']

We can also do this with for loops, but this numpy module is designed to carry out tasks like this only.

We will use numpy.where() to see the results.

arr = np.array([11, 12, 13, 14])
high_values = ['High', 'High', 'High', 'High']
low_values = ['Low', 'Low', 'Low', 'Low']
# numpy where() with condition argument
result = np.where(arr > 12,['High', 'High', 'High', 'High'],['Low', 'Low', 'Low', 'Low'])
print(result)

Using numpy.where() with single condition

We have converted the two arrays in a single array by using the where function like evaluating based on conditions of less than 12 and greater than 12.

The first value came out low because the value in the array arr is smaller than 12. Similarly, the last values returned are high because the value in array arr is greater than 12.

Let’s see how it worked.

Numpy.where() contains three arguments.

The first argument is the numpy array which got converted to a bool array.

arr > 12 ==> [False False True True]

Then numpy.where() iterated over the bool array and for every True, it yields corresponding element from list 1 i.e. high_values and for every False, it yields corresponding element from 2nd list i.e. low_values i.e.

[False False True True] ==> [‘Low’, ‘Low’, ‘High’, ‘High’]

This is how we created a new array from the older arrays.

Using numpy.where() with multiple conditions

In the above example, we have used single conditions. Here we will see the example with multiple conditions.

arr = np.array([11, 12, 14, 15, 16, 17])
# pass condition expression only
result = np.where((arr > 12) & (arr < 16),['A', 'A', 'A', 'A', 'A', 'A'],['B', 'B', 'B', 'B', 'B', 'B'])
print(result)

Using numpy.where() with multiple conditions

We executed multiple conditions on the array arr and it returned a bool value. Then numpy.where() iterated over the bool array and for every True it yields corresponding element from the first list and for every False it yields the corresponding element from the 2nd list. Then constructs a new array by the values selected from both the lists based on the result of multiple conditions on numpy array arr i.e.

  • Conditional expression returns true for 14 and 15 values, so they are replaced by values in list1.
  • Conditional expression returns False for 11,12,16, and 17, so they are replaced by values in list2.

Now, we will pass the different values and see what the array returns.

arr = np.array([11, 12, 14, 15, 16, 17])
# pass condition expression only
result = np.where((arr > 12) & (arr < 16),['A', 'B', 'C', 'D', 'E', 'F'],[1, 2, 3, 4, 5, 6])

Different values

Use np.where() to select indexes of elements that satisfy multiple conditions

We will take a new NumPy array:

arr = np.array([11, 12, 13, 14, 15, 16, 17, 15, 11, 12, 14, 15, 16, 17])

Now, we will give a condition and find the indexes of elements that satisfy that condition that is an element should be greater than 12 and less than 16. For this, we will use numpy.where(),

arr = np.array([11, 12, 13, 14, 15, 16, 17, 15, 11, 12, 14, 15, 16, 17])
# pass condition expression only
result = np.where((arr > 12) & (arr < 16))
print(result)

Use np.where() to select indexes of elements that satisfy multiple conditions

A tuple containing an array of indexes is returned where the conditions met True in the original array.

How did it work?

Here, the condition expression is evaluated to a bool numpy array, numpy.where() is passed to it. Then where() returned a tuple of arrays for each dimension. As our array was one dimension only, so it contained an element only i.e. a new array containing the indices of elements where the value was True in bool array i.e. indexes of items from original array arr where value is between 12 & 16.

Using np.where() without any condition expression

In this case, we will directly pass the bool array as a conditional expression.

result = np.where([True, False, False],[1, 2, 4],[7, 8, 9])
print(result)

Using np.where() without any condition expression

The True value is yielded from the first list and the False value is yielded from the second list when numpy.where()  iterates over the bool value.

So, basically, it returns an array of elements from the first list where the condition is True and elements from a second list elsewhere.

In the conclusion, we hope that you understood this article well.

numpy.where() – Explained with examples Read More »

Python Pandas : How to Drop rows in DataFrame by conditions on column values

How to Drop rows in DataFrame by conditions on column values in Python ?

In this article we will discuss how we can delete rows in a dataframe by certain conditions on column values.

DataFrame provides a member function drop() which is used to drop specified labels from rows or columns in dataframe.

DataFrame.drop(self, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’)

Let’s try with an example:

#Program :

import pandas as pd
#list of tuples
game = [('riya',37,'delhi','cat','rose'),
   ('anjali',28,'agra','dog','lily'),
   ('tia',42,'jaipur','elephant','lotus'),
   ('kapil',51,'patna','cow','tulip'),
   ('raj',30,'banglore','lion','orchid')]

#Create a dataframe object
df = pd.DataFrame(game, columns=['Name','Age','Place','Animal','Flower'], index=['a','b','c','d','e'])
print(df)
Output:
     Name  Age     Place       Animal       Flower
a    riya     37       delhi           cat             rose
b  anjali    28       agra           dog             lily
c     tia      42       jaipur     elephant        lotus
d   kapil    51      patna          cow           tulip
e     raj      30     banglore      lion          orchid

Delete rows based on condition on a column

Let’s try with an example by deleting a row:

deleteRow = df[df['Place'] == 'patna'].index
df.drop(deleteRow, inplace=True)
print(df)
Output:
 Name    Age     Place      Animal       Flower
a    riya    37     delhi           cat            rose
b  anjali   28      agra          dog            lily
c     tia     42      jaipur     elephant      lotus
e     raj     30    banglore      lion         orchid

Here, we give the condition i.e

df[‘Place’] == ‘patna’

Internally if we will see it is giving series object with True and False.

a   False
b   False
c   False
d   True
e   False

Name: Place, dtype: bool

Delete rows based on multiple conditions on a column :

Let’s try with multiple conditions

deleteRow = df[(df['Age'] >= 30) & (df['Age'] <= 40)].index
df.drop(deleteRow, inplace=True)
print(df)
Output:
    Name  Age     Place     Animal      Flower
b  anjali   28       agra        dog          lily 
c     tia     42       jaipur    elephant    lotus

Here, we join two conditions i.e df[‘Age’]>=30 and df[‘Age’]<=40 by putting ’&’ between two conditions.

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

Python Pandas : How to Drop rows in DataFrame by conditions on column values Read More »

pandas.apply(): Apply a function to each row/column in Dataframe

How to apply a function  to each row or column in Dataframe in Python.

To apply a function to each row or column data in a warframe be it lambda, user-defined or a numpy function we have to use a function from Python’s Pandas library.  The function belongs to the dataframe class .

Syntax-

DataFrame.apply(func, axis=0, broadcast=None, raw=False, reduce=None, result_type=None, args=(), **kwds)

Arguments :

  1. Func : It is the function that is to be applied to the rows/columns. It takes series as arguments and also returns series
  2. Axis : Axis is the axis in which the function is applied to the rows/columns. (default value is 0. If 1 means it applies to all rows, If 0 means it applies to all columns)
  3. Args : All the arguments passed in a list of tuples.

Apply a lambda function to each row or each column in Dataframe :

Let us consider a lambda function

lambda x : x + 10

Apply a lambda function to each column :

To apply the function to each column we just have to pass the lambda function as argument in the Dataframe.apply( ) function.

#Program :

import pandas as pd
import numpy as np
#list of tuples
matrix = [(222, 34, 23),
         (333, 31, 11),
         (444, 16, 21),
         (555, 32, 22),
         (666, 33, 27),
         (777, 35, 11)
         ]
#creating an object from Dataframe class
dfObj = pd.DataFrame(matrix, columns=list('abc'))
#Passing only the lambda function into the Dataframe function so that it gets applied to columns only
modMatrix = dfObj.apply(lambda x : x + 10)
print("After applying the lambda function to each column in dataframe")
print(modMatrix)
Output :

After applying the lambda function to each column in dataframe

     a      b   c
0  232  44  33
1  343  41  21
2  454  26  31
3  565  42  32
4  676  43  37
5  787  45  21

Apply a lambda function to each row :

To apply the function to each row we just have to add axis=1 and pass it to the lambda function with the lambda function in the Dataframe.apply( ) function like we did in the column.

#Program :

import pandas as pd
import numpy as np
#list of tuples
matrix = [(222, 34, 23),
         (333, 31, 11),
         (444, 16, 21),
         (555, 32, 22),
         (666, 33, 27),
         (777, 35, 11)
         ]
#creating an object from Dataframe class
dfObj = pd.DataFrame(matrix, columns=list('abc'))
#Passing only the lambda function into the Dataframe function so that it gets applied to columns only
modMatrix = dfObj.apply(lambda x : x + 10)
print("After applying the lambda function to each row in dataframe")
print(modMatrix)
Output :
After applying the lambda function to each row in dataframe
     a      b    c
0  227  39  28
1  338  36  16
2  449  21  26
3  560  37  27
4  671  38  32
5  782  40  16

Apply a User Defined function with or without arguments to each row or column of a Dataframe :

For this let us consider a user-defined function that multiplies the values by 2

def doubleData(x):

return x * 2

Apply a user-defined function to each column :

Like we applied the lambda function to each column, similarly we will only pass the function here.

#Program :

import pandas as pd
import numpy as np
# Multiply given value by 2 and returns
def doubleData(x):
   return x * 2
#list of tuples
matrix = [(222, 34, 23),
         (333, 31, 11),
         (444, 16, 21),
         (555, 32, 22),
         (666, 33, 27),
         (777, 35, 11)
         ]
#creating an object from Dataframe class
dfObj = pd.DataFrame(matrix, columns=list('abc'))
#Applyin the user defined function doubleData to columns only
modMatrix = dfObj.apply(doubleData)
print("After applying the user-defined function to each column in dataframe")
print(modMatrix)
Output :
After applying the user-defined function to each column in dataframe
      a      b    c
0   444  68  46
1   666  62  22
2   888  32  42
3  1110  64  44
4  1332  66  54
5  1554  70  22

Apply a user-defined function to each row :

We just have to add axis=1 to the above function to apply it to rows.

#Program :

import pandas as pd
import numpy as np
# Multiply given value by 2 and returns
def doubleData(x):
   return x * 2
#list of tuples
matrix = [(222, 34, 23),
         (333, 31, 11),
         (444, 16, 21),
         (555, 32, 22),
         (666, 33, 27),
         (777, 35, 11)
         ]
#creating an object from Dataframe class
dfObj = pd.DataFrame(matrix, columns=list('abc'))
#Applyin the user defined function doubleData to rows only
modMatrix = dfObj.apply(doubleData,axis=1)
print("After applying the user-defined function to each row in dataframe")
print(modMatrix)
Output :
After applying the user-defined function to each row in dataframe
      a      b    c
0   444  68  46
1   666  62  22
2   888  32  42
3  1110  64  44
4  1332  66  54
5  1554  70  22


Apply a user-defined function to each row or column with arguments :

Let us take a user defined function that takes accepts a series and a number, then returns the series multiplied to the number

#Program :

import pandas as pd
import numpy as np
#Multplies the whole seried with the number and return the series
def multiplyData(x, y):
   return x * y
#list of tuples
matrix = [(222, 34, 23),
         (333, 31, 11),
         (444, 16, 21),
         (555, 32, 22),
         (666, 33, 27),
         (777, 35, 11)
         ]
#creating an object from Dataframe class
dfObj = pd.DataFrame(matrix, columns=list('abc'))
#Applyin the user defined function with a argument
modMatrix = dfObj.apply(multiplyData, args=[4])
print("After applying the user-defined function with argument in dataframe")
print(modMatrix)
Output :
After applying the user-defined function with argument in dataframe
      a       b      c
0   888  136   92
1  1332  124   44
2  1776   64   84
3  2220  128   88
4  2664  132  108
5  3108  140   44

Apply a numpy functions to each row or column of a Dataframe

For this let’s use the numpy function numpy.square( ). (For columns pass the function directly and for rows add axis=1 and pass)

#Program

import pandas as pd
import numpy as np
#list of tuples
matrix = [(222, 34, 23),
         (333, 31, 11),
         (444, 16, 21),
         (555, 32, 22),
         (666, 33, 27),
         (777, 35, 11)
         ]
#creating an object from Dataframe class
dfObj = pd.DataFrame(matrix, columns=list('abc'))
#Applyin the numpy fuction .square()
modMatrix = dfObj.apply(np.square)
print("After applying the numpy function in dataframe")
print(modMatrix)
Output :
After applying the numpy function in dataframe
        a           b     c
0   49284  1156  529
1  110889   961  121
2  197136   256  441
3  308025  1024  484
4  443556  1089  729
5  603729  1225  121

Apply a Reducing functions to a to each row or column of a Dataframe

We passed a series into the user-defined functions and it also returned a series .  However, we can also pass a series and return a single variable. Let’s use numpy.sum( ) for that.

#Program :

import pandas as pd
import numpy as np
#list of tuples
matrix = [(222, 34, 23),
         (333, 31, 11),
         (444, 16, 21),
         (555, 32, 22),
         (666, 33, 27),
         (777, 35, 11)
         ]
#creating an object from Dataframe class
dfObj = pd.DataFrame(matrix, columns=list('abc'))
#Applyin the numpy fuction .sum()
modMatrix = dfObj.apply(np.sum)
print("After applying the numpy function in datframe")
print(modMatrix)
Output :
After applying the numpy function in datframe
a    2997
b     181
c     115
dtype: int64

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 – Modify a Dataframe

pandas.apply(): Apply a function to each row/column in Dataframe Read More »

How to Sort a List of Tuples by second Item

Python: How to Sort a List of Tuples by second Item

Tuples are a type of variable that allows you to store multiple items in a single variable. Tuple is one of four built-in data types in Python that are used to store data collections. The other three are List, Set, and Dictionary, all of which have different qualities and applications. A tuple is a collection that is both ordered and immutable.

The task is to write a Python program that sorts tuples by the second item in each tuple given a list of tuples.

Examples:

Input:

giventuple = [('Hello', 400), ('this', 500), ('is', 200), ('BTechGeeks', 100)]

Output:

[('BTechGeeks', 100), ('is', 200), ('Hello', 400), ('this', 500)]

Python program for Sorting a List of Tuples by the Second item

1)Key Function

When sorting a list, all of the list’s elements are compared to one another. However, before comparing the entries, it will call the key function on each entry to determine which portion of the object will be compared.

In other words, when an element is passed to the key function, it returns the element that should be used to compare the elements in the list while sorting.

2)Using lambda function

To sort a list of tuples by the second or ith item, we must include our custom comparator, i.e. key function, in the  sort () function.

We use lambda function as key function.

Below is the implementation:

# given tuple
giventuple = [('Hello', 400), ('this', 500), ('is', 200), ('BTechGeeks', 100)]
# using lambda function
giventuple.sort(key=lambda elem: elem[1])
# print giventuple
print(giventuple)

Output:

[('BTechGeeks', 100), ('is', 200), ('Hello', 400), ('this', 500)]

3)Using custom function as comparator

First, create a function that accepts a tuple and returns the second element.

Below is the implementation:

def comparator(elementtuple):
    return elementtuple[1]


# given tuple
giventuple = [('Hello', 400), ('this', 500), ('is', 200), ('BTechGeeks', 100)]
# using lambda function
giventuple.sort(key=comparator)
# print giventuple
print(giventuple)

Output:

[('BTechGeeks', 100), ('is', 200), ('Hello', 400), ('this', 500)]

Related Programs:

Python: How to Sort a List of Tuples by second Item Read More »

Different ways to Create a Tuple and Iterate over it

Python Tuple: Different ways to Create a Tuple and Iterate over it

Tuples are a type of variable that allows you to store multiple items in a single variable. Tuple is one of four built-in data types in Python that are used to store data collections. The other three are List, Set, and Dictionary, all of which have different qualities and applications. A tuple is a collection that is both ordered and immutable.

In this post we are going to discuss different ways to create the tuple and traverse through it.

Create a Tuple and Traverse it

1)List vs Tuple

  • Lists and tuples are represented in slightly different ways. Lists are commonly surrounded by the square bracket [], and elements are separated by commas. Tuples are surrounded by parenthesis (), and elements are separated by a comma. The parenthesis is optional, and these tuples are known as tuple packing.
  • It is the most significant distinh3ction between a list and a tuple, with lists being mutable and tuples being immutable. Lists are mutable, which means that the Python object can be modified after it is created, whereas tuples cannot be modified after they are created.
  • Tuples support fewer operations than lists. The built-in dir(object) function is used to retrieve all of the list and tuple’s supported functions.

2)Create a tuple of various types of elements

We can make a tuple of different elements by separating them with ‘,’ and wrapping them in braces i.e ( ).

Below is the implementation:

# Tuple
newtuple = ('hello', 3.5, 'this', 200, 'is', True, 'BTechGeeks')
# print tuple
print(newtuple)

Output:

('hello', 3.5, 'this', 200, 'is', True, 'BTechGeeks')

3)Create a tuple out of unpacked elements

We can also create a tuple from unpacked elements i.e without any braces just elements separated by comma.

Below is the implementation:

# Tuple
newtuple = 'hello', 3.5, 'this', 200, 'is', True, 'BTechGeeks'
# print tuple
print(newtuple)

Output:

('hello', 3.5, 'this', 200, 'is', True, 'BTechGeeks')

4)Create empty tuple

We can create tuple directly using () symbol.

Below is the implementation:

# creating new tuple
newtuple = ()
# print tuple
print(newtuple)

Output:

()

5)Convert list to tuple

We can convert list to tuple by using the syntax tuple(list_name).

Below is the implementation:

# given list
givenlist = [100, 'hello', 4.5, 'BTechGeeks']
# converting this list to tuple
newtuple = tuple(givenlist)
# print new tuple
print(newtuple)

Output:

(100, 'hello', 4.5, 'BTechGeeks')

6)Traverse the tuple

We can iterate over the tuple using for loop.

Below is the implementation:

# Tuple
newtuple = ('hello', 3.5, 'this', 200, 'is', True, 'BTechGeeks')
# Traverse the tuple
for i in newtuple:
    print(i)

Output:

hello
3.5
this
200
is
True
BTechGeeks

Related Programs:

Python Tuple: Different ways to Create a Tuple and Iterate over it Read More »

Python Set: remove() vs discard() vs pop()

A Python set is a list of things that are not in any particular order. – element in the set must be unique and immutable, and duplicate elements are removed from the sets. Sets are mutable, which means we can change them after they’ve been formed.

Unlike other Python sets, the elements of the set have no index, which means we can’t access any element of the set directly using the index. We may, however, print them all together or loop through the collection to get the list of elements.

Example:

Input:

givenset= {'This', 'is', 'BTechGeeks'} element='is'

Output:

{'BTechGeeks', 'this'}

Remove a element from the Set

There are several ways to remove a element from the set some of them are:

Method #1:Using discard() function

In Python, the built-in method discard() removes an element from a collection only if it is already present. If the element is missing from the list, no error or exception is thrown, and the original set is printed.
Implementing the discard() function if the element is present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'is'
# removing element which is in set using discard function.
givenset.discard(element)
# printing the set
print(givenset)

Output:

{'BTechGeeks', 'this'}

Implementing the discard() function if the element is not present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'hello'
# removing element which is not in set using discard function.
givenset.discard(element)
# printing the set
print(givenset)

Output:

{'is', 'this', 'BTechGeeks'}

Method #2:Using remove() function

In Python, the built-in method remove() removes an element from a set only if it is already present, similar to how the discard() method removes an element from a set. If the element is missing from the list, an error or exception is thrown.

Implementing the remove() function if the element is present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'is'
# removing element which is in set using remove() function.
givenset.remove(element)
# printing the set
print(givenset)

Output:

{'BTechGeeks', 'this'}

Implementing the remove() function if the element is not present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'hello'
# removing element which is not in set using remove() function.
givenset.remove(element)
# printing the set
print(givenset)

Output:

Traceback (most recent call last):
  File "/home/ebe45b71f9f465d547ea9cb944ebe071.py", line 6, in <module>
    givenset.remove(element)
KeyError: 'hello'

Method #3:Using pop() function

This operation takes an arbitrary element from the set and returns it.
It throws a KeyError if there are no elements to delete.

Implementing the pop() function if the element is present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# removing random element which is  in set using pop() function.
givenset.pop()
# printing the set
print(givenset)

Output:

{'is', 'BTechGeeks'}

 

 
Related Programs:

Python Set: remove() vs discard() vs pop() Read More »

Python Programming – Class Example

In this Page, We are Providing Python Programming – Class Example. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Class Example

Class example

Till now, some basic concepts of class has been discussed. The following example “ClassExample.py” defines’a class Person, which handles name and age of multiple individuals.

class Person: 
          " " "The program handles individual's data" " "
population=0

def ___init____ ( self , Name , Age ) : 
           " " "Initializes the data." " "
          self.name=Name
          self.age=Age
          Person.population+=1

def ___del___ ( self ) : 
         " " "Deleting the data." " "
        print ( ' Record of {0} is being removed'.format(self.name)) Person.population-=1

def AgeDetails ( self ) :
         ' ' 'Age details : ' ' ' 
       print ( ' { 0 } is { 1 } years old ' . format ( self . name , self . age ) )

def Records ( cls) : 
           " " "Print number of records." " "
          print ( ' There are {0} records ' . format ( cls.population ) )

records=classmethod ( Records )

print Person . ___doc___ 
record1=Person ( ' Ram ' , 26 )
print Person.AgeDetails. ___doc___ 
record1 . AgeDetails ( )
Person.records ( ) 
record2-Person ( ' Ahmed ' , 20 )
print record2 . AgeDetails. ___doc___ 
record2 . AgeDetails ( ) 
record2 . records ( ) 
record3=Person ( ' John ' , 22 )
print Person . AgeDetails. ___doc___ 
record3 . AgeDetails ( )
Person . records ( ) 
del recordl,record2 
Person . records ( )

The output is:

The program handles individual's data 
Age details :
Ram is 26 years old 
There are 1 records 
Age details :
Ahmed is 20 years old 
There are 2 records 
Age details : 
John ih 22 years old
There are 3 records 
Record of Ram is being removed 
Record of Ahmed is being removed 
There are 1 records

Variables defined in the class definition are class variables (population is a class variable); they are shared by all instances. To create instance variables (name and age are instance variables), they can be initialized in a method, e.g. self. name=value. Both class and instance variables are accessible through the notation self. name and an instance variable hide a class variable with the same name when accessed in this way. Therefore, the class variable population is better referred to as Person. population, and not-self. population. The instance variables name and age are referred to as self. name and self. age, respectively.

The Records is a method that belongs to the class and not to the instance. This is done by using classmethod ( ) built-in function. A class method receives the class as an implicit first argument, just like an instance method receives the instance. The class method can be called either on the class (Person. records ( )) or on an instance (record2 . records ( )). The instance is ignored except for its class.

The ___doc___ attribute is used to access docstrings of class (Person. ___doc___ ) and methods (record2 . AgeDetails . __doc___).

The ___del___ ( ) method is called when an instance is about to be destroyed. This is also called a destructor.

Python Programming – Class Example Read More »

Python Set: Remove Single or Multiple Elements from a Set?

A Python set is a list of things that are not in any particular order. – element in the set must be unique and immutable, and duplicate elements are removed from the sets. Sets are mutable, which means we can change them after they’ve been formed.

Unlike other Python sets, the elements of the set have no index, which means we can’t access any element of the set directly using the index. We may, however, print them all together or loop through the collection to get the list of elements.

Examples:

Removing single element from the set

Input:

givenset= {'this', 'is', 'BTechGeeks'} element='is'

Output:

{'BTechGeeks', 'this'}

Removing multiple elements from the set

Input:

givenset= {'Hello' ,'this', 'is', 'BTechGeeks'} element=['is' , 'this ']

Output:

{'BTechGeeks', 'hello'}

Remove one or more elements from a set

There are several ways to remove one or more elements from a set some of them are:

Method #1:Using discard() function to remove single element

In Python, the built-in method discard() removes an element from a collection only if it is already present. If the element is missing from the list, no error or exception is thrown, and the original set is printed.

Implementing the discard() function if the element is present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'is'
# removing element which is in set using discard function.
givenset.discard(element)
# printing the set
print(givenset)

Output:

{'BTechGeeks', 'this'}

Implementing the discard() function if the element is not present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'hello'
# removing element which is not in set using discard function.
givenset.discard(element)
# printing the set
print(givenset)

Output:

{'is', 'this', 'BTechGeeks'}

Method #2:Using remove() function to remove single element

In Python, the built-in method remove() removes an element from a set only if it is already present, similar to how the discard() method removes an element from a set. If the element is missing from the list, an error or exception is thrown.

Implementing the remove() function if the element is present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'is'
# removing element which is in set using remove() function.
givenset.remove(element)
# printing the set
print(givenset)

Output:

{'BTechGeeks', 'this'}

Implementing the remove() function if the element is not present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'hello'
# removing element which is not in set using remove() function.
givenset.remove(element)
# printing the set
print(givenset)

Output:

Traceback (most recent call last):
  File "/home/ebe45b71f9f465d547ea9cb944ebe071.py", line 6, in <module>
    givenset.remove(element)
KeyError: 'hello'

Method #3:Using pop() function to remove single element

This operation takes an arbitrary element from the set and returns it.
It throws a KeyError if there are no elements to delete.

Implementing the pop() function if the element is present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# removing random element which is  in set using pop() function.
givenset.pop()
# printing the set
print(givenset)

Output:

{'is', 'BTechGeeks'}

Method #4:Using difference_update() to remove multiple elements from the set

The Set class in Python has a function called difference update() that takes a sequence as an argument and removes all of the elements from the set. Let’s use this to remove all of the list’s elements from the set.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTechGeeks'}
# given list of elements to be deleted from set
elementslist = ['this', 'is']
# removing elements
givenset.difference_update(elementslist)
# printing the set
print(givenset)

Output:

{'BTechGeeks', 'hello'}

Method #5:Using discard() + for loop to remove multiple elements from set

Iterating over the elements to be removed and removing them one by one from the set  using discard() is another way to remove several elements from a set.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTechGeeks'}
# given list of elements to be deleted from set
elementslist = ['this', 'is']
# Traverse the elementslist which is to be deleted
for element in elementslist:
    # remove the element from set using discard
    givenset.discard(element)
# printing the set
print(givenset)

Output:

{'BTechGeeks', 'hello'}

Method #6:Using remove() + for loop to remove multiple elements from set

Iterating over the elements to be removed and removing them one by one from the set  using remove() is another way to remove several elements from a set.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTechGeeks'}
# given list of elements to be deleted from set
elementslist = ['this', 'is']
# Traverse the elementslist which is to be deleted
for element in elementslist:
    # remove the element from set using remove
    givenset.discard(element)
# printing the set
print(givenset)

Output:

{'hello', 'BTechGeeks'}

Related Programs:

Python Set: Remove Single or Multiple Elements from a Set? Read More »

Python : How to copy a dictionary | Shallow Copy vs Deep Copy

Dictionaries are Python’s implementation of an associative array data structure. A dictionary is a grouping of key-value pairs. Each key pair is represented by a key pair and its associated value.

A dictionary is defined by a list of key value pairs enclosed in curly braces and separated by a comma. The value of each key is separated by the column ‘:’.

It is not possible to sort a dictionary solely to obtain a representation of the sorted dictionary. Dictionary entries are ordered by default, but other data types, such as lists and tuples, are not. As a result, you’ll need an ordered data form like a list—most likely a list of tuples.

Examples:

Input:

dictionary = {'this': 200, 'is':100, 'BTechGeeks':300}

Output:

Old dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}
New dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}

Copy a Dictionary:

There are several ways to copy a dictionary some of them are:

Method #1:Using loop and copying element by element

This technique involves traversing the entire dictionary and copying each and every element pointed by the key to a previously declared new dictionary.

Approach:

  • Take a empty new dictionary.
  • Traverse the old dictionary using for loop.
  • Copy the key and value of old dictionary element by element.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# Take a empty dictionary
newdict = {}
# Traverse the old dictionary
for key in dictionary:
    newdict[key] = dictionary[key]
# print old dictionary
print("Old dictionary : ", dictionary)
# print new dictionary
print("New dictionary : ", newdict)

Output:

Old dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}
New dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}

Method #2: Using = operator

We can simply copy a dictionary using = operator.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# copying dictionary to new dictionary
newdict = dictionary
# print old dictionary
print("Old dictionary : ", dictionary)
# print new dictionary
print("New dictionary : ", newdict)

Output:

Old dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}
New dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}

Explanation:

  • We begin by creating a dictionary dictionary. And then use the code line newlist=dictionary to copy it to a new object dict2.
  • This procedure copies each object’s references from dictionary to the new dictionary newdict.
  • As a consequence, changing any aspect of newdict will change dictionary and vice versa.
    The above code shows that when we update any(iterable or non-iterable) object in newdict, the same change is seen in dictionary.

Method #3: Using copy() to create a shallow copy of dictionary

A shallow copy is when a new dictionary object is formed and references to existing dictionary objects are inserted into it.

In Python, the dictionary copy() method creates a shallow copy of the given dictionary. It’s identical to what we saw before when copying elements by traversing through a dictionary.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# copying dictionary to new dictionary using copy
newdict = dictionary.copy()
# updating new dictionary
newdict['hello'] = 400
# print old dictionary
print("Old dictionary : ", dictionary)
# print new dictionary
print("New dictionary : ", newdict)

Output:

Old dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}
New dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300, 'hello': 400}

Explanation:

  • We initialize the dictionary dictionary with any values. To make a shallow copy, use the copy() method on it.
  • We update the new elements and see the corresponding shift in the original dictionary after the copy is made.
  • Changes in non-iterable elements of newdict have no impact on the original dictionary, just as they do with the element-by-element copying technique.
  • The change is reflected in the given dictionary, dictionary, for iterable ones like lists.

Method #4: Using copy.deepcopy()  to copy a dictionary

In Python, the deepcopy() method is part of the copy module. It creates a new dictionary from the passed dictionary’s elements. This method recursively copies all of the elements of the given dictionary.

Below is the implementation:

# importing copy
import copy
# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# copying dictionary to new dictionary using deepcopy
newdict = copy.deepcopy(dictionary)
# updating new dictionary
newdict['hello'] = 400
# print old dictionary
print("Old dictionary : ", dictionary)
# print new dictionary
print("New dictionary : ", newdict)

Output:

Old dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}
New dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300, 'hello': 400}

Related Programs:

Python : How to copy a dictionary | Shallow Copy vs Deep Copy Read More »

Python Object Oriented Programming

In this Page, We are Providing Python Programming – Object Oriented Programming. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Object Oriented Programming

Object-oriented programming (OOP) is a programming paradigm that represents concepts as “objects”, that have attributes that describe the object in the form of data attributes and associated procedures known as methods. As mentioned in chapter 1, Python is an OOP language. In Python, class form the basis of OOP. Some of the features of OOP language are:

  • Inheritance
  • Polymorphism
  • Encapsulation

Some of the advantages of the OOP approach are:

– Reusability: A part of a code can be reused for accommodating new functionalities with little or no changes.
– Maintenance: If some modification is made in the base class, the effect gets reflected automatically into the derived class, thus, the code maintenance is significantly less hectic.
– Faster output: With organized and methodical coding, there is little room for error, and as a result programmer can work comfortably, resulting in fast and efficient output.

Method object

In the MyClass example, x. f is a method object and x. f ( ) returns the string ‘hello world’. The call x. f ( ) is exactly equivalent to MyClass . f (x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument

>>> x . f ( )
' hello world '
>>> x . f ( )==MyClass . f ( x )
True

The method object can be stored and can be called later.

>>> xf=x . f 
>>> print xf ( )
hello world
>>> type ( xf )
<type ' instancemethod ' >

Python Programming OOP

Python Object Oriented Programming Read More »