Python

Python Set intersection() Method with Examples

Prerequisite:

Python set() Function with Examples

Set intersection() Method in Python:

The intersection() method returns a set containing the similarity(common items) of two or more sets.

If the comparison is done with more than two sets, the returned set contains only items that exist in both sets, or in all sets if the comparison is done with more than two sets.

For Example:

If P and Q are two distinct sets. A set intersection between P and Q is :

Let P={4,5,6,7}

Q={5,6,8,9}

P intersection Q = {5,6}

Since {5,6} are only the common elements in both the sets

Syntax:

set.intersection(set1, set2,..........)

Parameters

set1: This is Required. The set to look for similar items in

set2: This is Optional. The other set to look for similar items in. You are free to compare as many sets as you want. Use a comma to separate the sets.

Return Value:

The intersection() method returns the intersection of set A and all the other sets (passed as argument).

If the argument is not passed to an intersection(), a shallow copy of the set is returned (A).

Examples:

Example1:

Input:

Given first set =  {10, 20, 30, 40, 50}
Given second set = {100, 20, 80, 70, 30}
Given third set = {200, 40, 80, 30}

Output:

firstset intersection secondset =  {20, 30}
firstset intersection thirdset =  {40, 30}
secondset intersection thirdset =  {80, 30}

Example2:

Input:

Given first set =  {'a', 'b', 'c'}
Given second set = {'p', 'q', 'r'}
Given third set = {'q', 'a', 'k'}

Output:

firstset intersection secondset =  set()
firstset intersection thirdset =  {'a'}
secondset intersection thirdset =  {'q'}

Set intersection() Method with Examples in Python

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

Approach:

  • Give the first set as static input and store it in a variable.
  • Give the second set as static input and store it in another variable.
  • Give the third set as static input and store it in another variable.
  • Get the intersection(common elements) of the first set and second set using the intersection () method and print it.
  • Get the intersection(common elements) of the first set and third set using the intersection () method and print it.
  • Get the intersection(common elements) of the second set and third set using the intersection () method and print it.
  • The Exit of the Program.

Below is the implementation:

# Give the first set as static input and store it in a variable.
fst_set = {10, 20, 30, 40, 50}
# Give the second set as static input and store it in another variable.
scnd_set = {100, 20, 80, 70, 30}
# Give the third set as static input and store it in another variable.
thrd_set = {200, 40, 80, 30}
# Get the intersection(common elements) of the first set and second set using
# the intersection () method and print it.
print("firstset intersection secondset = ", fst_set.intersection(scnd_set))
# Get the intersection(common elements) of the first set and third set using
# the intersection () method and print it.
print("firstset intersection thirdset = ", fst_set.intersection(thrd_set))
# Get the intersection(common elements) of the second set and third set using
# the intersection () method and print it.
print("secondset intersection thirdset = ", scnd_set.intersection(thrd_set))

Output:

firstset intersection secondset =  {20, 30}
firstset intersection thirdset =  {40, 30}
secondset intersection thirdset =  {80, 30}

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

Approach:

  • Give the first set as user input using set(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the second set as user input using set(),map(),input(),and split() functions.
  • Store it in another variable.
  • Give the third set as user input using set(),map(),input(),and split() functions.
  • Store it in another variable.
  • Get the intersection(common elements) of the first set and second set using the intersection () method and print it.
  • Get the intersection(common elements) of the first set and third set using the intersection () method and print it.
  • Get the intersection(common elements) of the second set and third set using the intersection () method and print it.
  • The Exit of the Program.

Below is the implementation:

# Give the first set as user input using set(),map(),input(),and split() functions.
# Store it in a variable.
fst_set = set(map(int, input(
   'Enter some random Set Elements separated by spaces = ').split()))
# Give the second set as user input using set(),map(),input(),and split() functions.
# Store it in another variable.
scnd_set = set(map(int, input(
   'Enter some random Set Elements separated by spaces = ').split()))
# Give the third set as user input using set(),map(),input(),and split() functions.
# Store it in another variable.
thrd_set = set(map(int, input(
   'Enter some random Set Elements separated by spaces = ').split()))
   
# Get the intersection(common elements) of the first set and second set using
# the intersection () method and print it.
print("firstset intersection secondset = ", fst_set.intersection(scnd_set))
# Get the intersection(common elements) of the first set and third set using
# the intersection () method and print it.
print("firstset intersection thirdset = ", fst_set.intersection(thrd_set))
# Get the intersection(common elements) of the second set and third set using
# the intersection () method and print it.
print("secondset intersection thirdset = ", scnd_set.intersection(thrd_set))

Output:

Enter some random Set Elements separated by spaces = 1 2 3
Enter some random Set Elements separated by spaces = 1 5 7
Enter some random Set Elements separated by spaces = 9 8 0
firstset intersection secondset = {1}
firstset intersection thirdset = set()
secondset intersection thirdset = set()

 

 

Python Set intersection() Method with Examples Read More »

Python Set difference_update() Method with Examples

Prerequisite:

Python set() Function with Examples

Set difference_update() Method in Python:

The difference_update() method removes items from both sets.

The difference_update() method differs from the difference() method in that the difference() method returns a new set that does not include the unwanted items, whereas the difference_update() method removes the unwanted items from the original set.

For Example

If P and Q are two distinct sets. A set difference between P and Q is a set of elements that exist only in set P but not in set Q.

The difference_update() replaces set P with the P-Q set difference.

Syntax:

set.difference_update(set)

Parameters

set: This is Required. The set used to look for differences.

Return Value:

difference_update() produces a result None, indicating that the object (set) has been mutated.

Let P, Q be two sets

When you execute the code,

  • The result is None.
  • P will be updated to P-Q.
  • Q will remain unchanged.

Examples:

Example1:

Input:

Given first set = {10, 11, 12, 13}
Given second set = {11, 12, 20, 14}

Output:

The given first set is : {10, 13}
The given second set is : {11, 12, 20, 14}
The result after applying difference_update method:  None

Explanation:

Here it removes the common elements{11, 12} from the first set and
updates the given first set as {10, 13}.

Example2:

Input:

Given first set = {20, 30, 40, 20, 30, 50, 60}
Given second set = {40, 50, 60, 100, 80}

Output:

The given first set is : {20, 30}
The given second set is : {100, 40, 80, 50, 60}
The result after applying difference_update method:  None

Set difference_update() Method with Examples in Python

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

Approach:

  • Give the first set as static input and store it in a variable.
  • Give the second set as static input and store it in another variable.
  • Apply the difference_update() method to the given first and second sets.
  • Store it in another variable.
  • Print the given first set.
  • Print the second set.
  • Print the above result after applying the difference_update() method for the given sets.
  • The Exit of the Program.

Below is the implementation:

# Give the first set as static input and store it in a variable.
fst_Set = {10, 11, 12, 13}
# Give the second set as static input and store it in another variable.
scnd_set = {11, 12, 20, 14}
# Apply the difference_update() method to the given first and second sets.
# Store it in another variable.
rslt = fst_Set.difference_update(scnd_set)
# print the given first set.
print("The given first set is :", fst_Set)
# print the given second set.
print("The given second set is :", scnd_set)
# Print the above result after applying difference_update() method for the given sets.
print("The result after applying difference_update method: ", rslt)

Output:

The given first set is : {10, 13}
The given second set is : {11, 12, 20, 14}
The result after applying difference_update method:  None

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

Approach:

  • Give the first set as user input using set(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the second set as user input using set(),map(),input(),and split() functions.
  • Store it in another variable.
  • Apply the difference_update() method to the given first and second sets.
  • Store it in another variable.
  • Print the given first set.
  • Print the second set.
  • Print the above result after applying the difference_update() method for the given sets.
  • The Exit of the Program.

Below is the implementation:

# Give the first set as user input using set(),map(),input(),and split() functions.
# Store it in a variable.
fst_set = set(map(int, input(
   'Enter some random Set Elements separated by spaces = ').split()))
# Give the second set as user input using set(),map(),input(),and split() functions.
# Store it in another variable.
scnd_set = set(map(int, input(
   'Enter some random Set Elements separated by spaces = ').split()))
# Apply the difference_update() method to the given first and second sets.
# Store it in another variable.
rslt = fst_set.difference_update(scnd_set)
# print the given first set.
print("The given first set is :", fst_set)
# print the second first set.
print("The given second set is :", scnd_set)
# Print the above result after applying difference_update method for the given sets.
print("The result after applying difference_update method: ", rslt)

Output:

Enter some random Set Elements separated by spaces = 10 20 15 16
Enter some random Set Elements separated by spaces = 20 15 16 80
The given first set is : {10}
The given second set is : {16, 80, 20, 15}
The result after applying difference_update method: None

Python Set difference_update() Method with Examples Read More »

Python Set difference() Method with Examples

Prerequisite:

Python set() Function with Examples

Set difference() Method in Python:

The difference() method returns a set containing the difference of two sets.

The returned set contains items that only exist in the first set and not in both.

For Example:

If P and Q are two distinct sets. A set difference between P and Q is a set of elements that exist only in the set P but not in the set Q.

Let P={4,5,6,7}

Q={5,6,8,9}

P-Q={4,7}

Q-P ={8,9}

Syntax:

set.difference(set)

Parameters

set: This is Required. The set used to look for differences.

Return Value:

difference() computes the difference between two sets, each of which is a set. It makes no changes to the original sets.

Examples:

Example1:

Input:

Given first set = {10, 11, 12, 13}
Given second set = {11, 12, 20, 14}

Output:

firstset-secondset :  {10, 13}
secondset-firstset :  {20, 14}

Example2:

Input:

Given first set = {20, 30, 40, 20, 30, 50, 60}
Given second set = {40, 50, 60, 100, 80}

Output:

firstset-secondset :  {20, 30}
secondset-firstset :  {80, 100}

Set difference() Method with Examples in Python

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

1)Set Difference Using difference() method

Approach:

  • Give the first set as static input and store it in a variable.
  • Give the second set as static input and store it in another variable.
  • Get the difference between the( first set – second set ) using the difference() method.
  • Store it in another variable.
  • Get the difference between the (second set – first set ) using the difference() method.
  • Store it in another variable.
  • Print the result (first set – second set).
  • Print the result (second set – first set ).
  • The Exit of the Program.

Below is the implementation:

# Give the first set as static input and store it in a variable.
fst_Set = {10, 11, 12, 13}
# Give the second set as static input and store it in another variable.
scnd_set = {11, 12, 20, 14}
# Get the difference between the( first set - second set ) using the difference()
# method.
# Store it in another variable.
rslt1 = fst_Set.difference(scnd_set)
# Get the difference between the (second set - first set ) using the difference()
# method.
# Store it in another variable.
rslt2 = scnd_set.difference(fst_Set)
# Print the result (first set - second set).
print("firstset-secondset : ", rslt1)
# Print the result (second set - first set ).
print("secondset-firstset : ", rslt2)

Output:

firstset-secondset :  {10, 13}
secondset-firstset :  {20, 14}
2)Set Difference Using ‘-‘ Operator

Approach:

  • Give the first set as static input and store it in a variable.
  • Give the second set as static input and store it in another variable.
  • Get the difference between the( first set – second set ) using the ‘-‘ operator and print it.
  • Get the difference between the (second set – first set ) using the ‘-‘ operator and print it.
  • The Exit of the Program.

Below is the implementation:

# Give the first set as static input and store it in a variable.
fst_set = {'u', 'v', 'w', 'x', 'y', 'u'}
# Give the second set as static input and store it in another variable.
scnd_set = {'w', 'z', 'x', 'a'}
# Get the difference between the( first set - second set ) using the '-' operator
# and print it
print("firstset-secondset : ", fst_set-scnd_set)
# Get the difference between the (second set - first set ) using the '-' operator
# print it.
print("secondset-firstset : ", scnd_set-fst_set)

Output:

firstset-secondset :  {'y', 'v', 'u'}
secondset-firstset :  {'z', 'a'}

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

1)Set Difference Using difference() method

Approach:

  • Give the first set as user input using set(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the second set as user input using set(),map(),input(),and split() functions.
  • Store it in another variable.
  • Get the difference between the( first set – second set ) using the difference() method.
  • Store it in another variable.
  • Get the difference between the (second set – first set ) using the difference() method.
  • Store it in another variable.
  • Print the result (first set – second set).
  • Print the result (second set – first set ).
  • The Exit of the Program.

Below is the implementation:

# Give the first set as user input using set(),map(),input(),and split() functions.
# Store it in a variable.
fst_set = set(map(int, input(
   'Enter some random Set Elements separated by spaces = ').split()))
# Give the second set as user input using set(),map(),input(),and split() functions.
# Store it in another variable.
scnd_set = set(map(int, input(
   'Enter some random Set Elements separated by spaces = ').split()))
# Get the difference between the( first set - second set ) using the difference()
# method.
# Store it in another variable.
rslt1 = fst_set.difference(scnd_set)
# Get the difference between the (second set - first set ) using the difference()
# method.
# Store it in another variable.
rslt2 = scnd_set.difference(fst_set)
# Print the result (first set - second set).
print("firstset-secondset : ", rslt1)
# Print the result (second set - first set ).
print("secondset-firstset : ", rslt2)

Output:

Enter some random Set Elements separated by spaces = 20 30 40 10 10
Enter some random Set Elements separated by spaces = 60 50 20 30
firstset-secondset : {40, 10}
secondset-firstset : {50, 60}
2)Set Difference Using ‘-‘ Operator

Approach:

  • Give the first set as user input using set(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the second set as user input using set(),map(),input(),and split() functions.
  • Store it in another variable.
  • Get the difference between the( first set – second set ) using the ‘-‘ operator and print it.
  • Get the difference between the (second set – first set ) using the ‘-‘ operator and print it.
  • The Exit of the Program.

Below is the implementation:

# Give the first set as user input using set(),map(),input(),and split() functions.
# Store it in a variable.
fst_set = set(map(int, input(
   'Enter some random Set Elements separated by spaces = ').split()))
# Give the second set as user input using set(),map(),input(),and split() functions.
# Store it in another variable.
scnd_set = set(map(int, input(
   'Enter some random Set Elements separated by spaces = ').split()))
# Get the difference between the( first set - second set ) using the '-' operator
# and print it
print("firstset-secondset : ", fst_set-scnd_set)
# Get the difference between the (second set - first set ) using the '-' operator
# print it.
print("secondset-firstset : ", scnd_set-fst_set)

Output:

Enter some random Set Elements separated by spaces = 10 10 13 15
Enter some random Set Elements separated by spaces = 12 15
firstset-secondset : {10, 13}
secondset-firstset : {12}

 

 

Python Set difference() Method with Examples Read More »

Python Dictionary values() Function with Examples

Dictionary values() Function in Python:

The values() method returns a view object that displays a list of all the dictionary’s values.

Syntax:

dictionary.values()

Parameters: This method doesn’t accept any parameters

Return Value:

The values() method returns a view object containing a list of all values in a given dictionary.

Examples:

Example1:

Input:

Given dictionary = {20: 'good', 30: 'morning', 40: 'btechgeeks'}

Output:

The values of the given dictionary is:
dict_values(['good', 'morning', 'btechgeeks'])

Example2:

Input:

Given dictionary = {'hello': 1, 'this': 3, 'is': 4, 'btechgeeks': 8}

Output:

The values of the given dictionary is:
dict_values([1, 3, 4, 8])

Dictionary values() Function with Examples in Python

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

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Get all the values of the given dictionary using the values() method.
  • Store it in another variable.
  • Print all the values of the given dictionary.
  • The Exit of the Program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict = {20: 'good', 30: 'morning', 40: 'btechgeeks'}
# Get all the values of the given dictionary using the values() method.
# Store it in another variable.
dict_valus = gvn_dict.values()
# Print all the values of the given dictionary.
print("The values of the given dictionary is:")
print(dict_valus)

Output:

The values of the given dictionary is:
dict_values(['good', 'morning', 'btechgeeks'])

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

Approach:

  • Take a dictionary and initialize it with an empty dictionary using dict() or {}.
  • Give the number of keys as user input using int(input()) and store it in a variable.
  • Loop till the given number of keys using for loop.
  • Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
  • Initialize the key with the value of the dictionary.
  • Get all the values of the given dictionary using the values() method.
  • Store it in another variable.
  • Print all the values of the given dictionary.
  • The Exit of the Program.

Below is the implementation:

# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = {}
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
    input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
        # Inside the for loop scan the key and value as
    # user input using input(),split() functions
    # and store them in two separate variables.
    keyy, valuee = input(
        'Enter key and value separated by spaces = ').split()
    # Initialize the key with the value of the dictionary.
    gvn_dict[keyy] = valuee

# Get all the values of the given dictionary using the values() method.
# Store it in another variable.
dict_valus = gvn_dict.values()
# Print all the values of the given dictionary.
print("The values of the given dictionary is:")
print(dict_valus)

Output:

Enter some random number of keys of the dictionary = 4
Enter key and value separated by spaces = hello 350
Enter key and value separated by spaces = this 450
Enter key and value separated by spaces = is 550
Enter key and value separated by spaces = btechgeeks 650
The values of the given dictionary is:
dict_values(['350', '450', '550', '650'])

Python Dictionary values() Function with Examples Read More »

Python Dictionary copy() Function with Examples

Dictionary copy() Function in Python:

The copy() method makes a duplicate of the specified dictionary(copy).

Syntax:

dictionary.copy()

Parameters: This method doesn’t accept any parameters

Return Value:

This method gives you a shallow copy of the dictionary. It makes no changes to the original dictionary.

Examples:

Example1:

Input:

Given dictionary = {20: 'good', 30: 'morning', 40: 'btechgeeks'}

Output:

The given original dictionary is:
{20: 'good', 30: 'morning', 40: 'btechgeeks'}
The copied new dictionary is:
{20: 'good', 30: 'morning', 40: 'btechgeeks'}

Example2:

Input:

Given dictionary = {'hello': 100, 'btechgeeks': 200}

Output:

The given original dictionary is:
{'hello': 100, 'btechgeeks': 200}
The copied new dictionary is:
{'hello': 100, 'btechgeeks': 200}

Dictionary copy() Function with Examples in Python

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

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Copy the given dictionary into a new dictionary using the copy() function.
  • Store it in another variable.
  • Print the given original dictionary.
  • Print the copied new dictionary.
  • The Exit of the Program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict = {20: 'good', 30: 'morning', 40: 'btechgeeks'}
# Copy the given dictionary into a new dictionary using the copy() function.
# Store it in another variable.
new_dict = gvn_dict.copy()
# Print the given original dictionary.
print("The given original dictionary is:")
print(gvn_dict)
# Print the copied new dictionary.
print("The copied new dictionary is:")
print(new_dict)

Output:

The given original dictionary is:
{20: 'good', 30: 'morning', 40: 'btechgeeks'}
The copied new dictionary is:
{20: 'good', 30: 'morning', 40: 'btechgeeks'}
Difference between Dictionary copy() Function , = Operator

When the copy() method is used, a new dictionary is created that contains a copy of the original dictionary’s references.
When the = operator is used, it creates a new reference to the original dictionary.

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Copy the given dictionary into a new dictionary using the ‘=’ Operator.
  • Store it in another variable.
  • Remove all the elements from the new dictionary using the clear() function.
  • Print the given original dictionary.
  • Print the copied new dictionary.
  • The Exit of the Program.
# Give the dictionary as static input and store it in a variable.
gvn_dict = {'hello': 100, 'btechgeeks': 200}
# Copy the given dictionary into a new dictionary using the '=' Operator.
# Store it in another variable.
new_dict = gvn_dict
# Remove all the elements from the new dictionary using the clear() function.
new_dict.clear()
# Print the given original dictionary.
print("The given original dictionary is:")
print(gvn_dict)
# Print the copied new dictionary.
print("The copied new dictionary is:")
print(new_dict)

Output:

The given original dictionary is:
{}
The copied new dictionary is:
{}

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

Approach:

  • Take a dictionary and initialize it with an empty dictionary using dict() or {}.
  • Give the number of keys as user input using int(input()) and store it in a variable.
  • Loop till the given number of keys using for loop.
  • Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
  • Initialize the key with the value of the dictionary.
  • Copy the given dictionary into a new dictionary using the copy() function.
  • Store it in another variable.
  • Print the given original dictionary.
  • Print the copied new dictionary.
  • The Exit of the Program.

Below is the implementation:

# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = {}
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
    input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
        # Inside the for loop scan the key and value as
    # user input using input(),split() functions
    # and store them in two separate variables.
    keyy, valuee = input(
        'Enter key and value separated by spaces = ').split()
    # Initialize the key with the value of the dictionary.
    gvn_dict[keyy] = valuee

# Copy the given dictionary into a new dictionary using the copy() function.
# Store it in another variable.
new_dict = gvn_dict.copy()
# Print the given original dictionary.
print("The given original dictionary is:")
print(gvn_dict)
# Print the copied new dictionary.
print("The copied new dictionary is:")
print(new_dict)

Output:

Enter some random number of keys of the dictionary = 2
Enter key and value separated by spaces = 100 hello
Enter key and value separated by spaces = 200 btechgeeks
The given original dictionary is:
{'100': 'hello', '200': 'btechgeeks'}
The copied new dictionary is:
{'100': 'hello', '200': 'btechgeeks'}

 

 

Python Dictionary copy() Function with Examples Read More »

Python str() Function with Examples

str() Function in Python:

The str() function returns a string from the specified value.

Syntax:

str(object, encoding=encoding, errors=errors)

Parameters

object: It may be any object. The object to be converted into a string is specified.

encoding: The object’s encoding. UTF-8 is the default.

errors: Specifies what should be done if the decoding fails.

Errors are classified into six types:

strict – the default response, which throws a UnicodeDecodeError exception if it fails.

ignore – removes any unencodable Unicode from the output.

replace – converts an unencodable Unicode character to a question mark.

xmlcharrefreplace – inserts an XML character reference rather than an unencodable Unicode character.

backslashreplace – replaces unencodable Unicode with an /uNNNN espace sequence.

namereplace – replaces unencodable Unicode with an N… escape sequence.

Return Value:

The str() method returns a string, which is an informal or nicely printable representation of the object passed in.

Examples:

Example1:

Input:

Given Number = 25

Output:

The given number after converting it into a string =  25
<class 'str'>

Example2:

Input:

Given Number = 80

Output:

The given number after converting it into a string =  80
<class 'str'>

str() Function with Examples in Python

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

Approach:

  • Give the number as static input and store it in a variable.
  • Pass the given number as an argument to the str() function that converts the given number into a string. (integer to string)
  • Store it in another variable.
  • Print the given number after converting it into a string.
  • Print the type of the above result (string number).
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 25
# Pass the given number as an argument to the str() function that converts
# the given number into a string. (integer to string)
# Store it in another variable.
str_numb = str(gvn_numb)
# Print the given number after converting it into a string.
print("The given number after converting it into a string = ", str_numb)
# Print the type of the above result.(string number)
print(type(str_numb))

Output:

The given number after converting it into a string =  25
<class 'str'>
str() for bytes

If both the encoding and errors parameters are specified, the first parameter, object, must be a bytes-like-object (bytes or bytearray).

If the object is bytes or bytearray, str() calls bytes internally.

bytes.decode(encoding, errors)

Otherwise, it loads the bytes object into the buffer before invoking the decode() method.

# str() for bytes
k = bytes('Prögrams', encoding='utf-8')
print(str(k, encoding='ascii', errors='ignore'))

Output:

Prgrams

Explanation:

ASCII cannot decode the character ‘ö’ in this case. As a result, it should throw an error. We have, however, set the errors to ‘ignore’. As a result, Python ignores the character that cannot be decoded by str ().

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.
  • Pass the given number as an argument to the str() function that converts the given number into a string. (integer to string)
  • Store it in another variable.
  • Print the given number after converting it into a string.
  • Print the type of the above result (string 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_numb = int(input("Enter some random number = "))
# Pass the given number as an argument to the str() function that converts
# the given number into a string. (integer to string)
# Store it in another variable.
str_numb = str(gvn_numb)
# Print the given number after converting it into a string.
print("The given number after converting it into a string = ", str_numb)
# Print the type of the above result.(string number)
print(type(str_numb))

Output:

Enter some random number = 70
The given number after converting it into a string = 70
<class 'str'>

Python str() Function with Examples Read More »

Python property() Function with Examples

property() Function in Python:

The property() construct returns the attribute of the property.

Syntax:

property(fget=None, fset=None, fdel=None, doc=None)

Parameters

The property() function accepts four optional parameters:

fget (Optional): Function for obtaining the value of an attribute. None is the default value.
fset (Optional): A function for setting the value of an attribute. None is the default value.
fdel (Optional): Deletes the attribute value. doc (optional) – A string containing the documentation (docstring) for the attribute. None is the default value.

doc (Optional): A string containing the attribute’s documentation (docstring). None is the default value.

Return Value:

property() function returns the property attribute based on the getter, setter, and deleter arguments.

  • If no arguments are provided, property() returns a base property attribute with no getter, setter, or deleter.
  • If doc is not provided, property() uses the getter function’s docstring.

property() Function with Examples in Python

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

Approach:

  • Create a class name as an Employee.
  • Inside the class, create a function say getName().
  • Inside the getName() function print some random text like ‘Get the employee Name’.
  • Return the name value of the given class.
  • Create another function say setName() which accepts the given value as an argument.
  • Print the given value.
  • Set the name as the given value.
  • Create another function say delName().
  • Inside the delName() function print some random text.
  • Delete the given name using the del function.
  • Set or configure property to use getName, setName and delName methods
  • Create an object for the given class person by passing some random name as an argument.
  • Print the name of the above object.
  • Modify the name of the above object with some random name.
  • Delete the name of the above object.
  • The Exit of the Program.

Below is the implementation:

# Create a class name as an Employee.
class Employee:
    def __init__(self, ename):
        self.empname = ename

    # Inside the class, create a function say getName().
    def getName(self):
        # Inside the getName() function print some random text like
        # 'Get the employee Name'.
        print('Get the employee Name :')
        # Return the name value of the given class.
        return self.empname
   # Create another function say setName() which accepts the given value as
   # an argument.

    def setName(self, val):
        # Print the given value.
        print('Set the employee Name : ' + val)
        # Set the name as the given value.
        self.empname = val

    # Create another function say delName().
    def delName(self):
        # Inside the delName() function print some random text.
        print('Delete the employee Name ')
        # Delete the given name using the del function.
        del self.empname

    # Set or configure property to use getName, setName
    # and delName methods
    ename = property(getName, setName, delName, 'Name property')


# Create an object for the given class person by passing some random name as
# argument.
e = Employee('Dhoni')
# Print the name of the above object.
print(e.ename)
# Modify the name of the above object with some random name.
e.ename = 'Virat'
# Delete the name of the above object.
del e.ename

Output:

Get the employee Name :
Dhoni
Set the employee Name : Virat
Delete the employee Name

Explanation:

In this case, empname is used as a private variable to store Employee name.

We also established or set:

  • A getter method getName() for obtaining the Employee name.
  • A setter method setName() for setting the Employee name.
  • A deleter method delName() for deleting the Employee name.

By calling the property() method, we can now set a new property attribute name.

Referencing e.ename, as shown in the program, internally calls getName() as a getter, setName() as a setter, and delName() as deleter via the printed output present inside the methods.

Python property() Function with Examples Read More »

Python object() Function with Examples

object() Function in Python:

The function object() returns an empty object.

This object cannot be extended with new properties or methods.

This object serves as the foundation for all classes; it contains the built-in properties and methods that are the default for all classes.

Syntax:

object()

Parameters: This function has no Parameters.

Return Value:

The object() function returns an object with no features.

object() Function with Examples in Python

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

Approach:

  • Take a variable and initialize it with the object() function.
  • Pass the above result as an argument to the type() function to get the type of the above object.
  • Store it in a variable.
  • Pass the above result as an argument to the dir() function to get all the attributes.
  • Store it in another variable.
  • Print the type of the result object.
  • Print all the attributes (dir) of the result object.
  • The Exit of the Program.

Below is the implementation:

# Take a variable and initialize it with the object() function.
m = object()
# Pass the above result as an argument to the type() function to get the type
# of the above object.
# Store it in a variable.
obj_type = type(m)
# Pass the above result as an argument to the dir() function to get all the
# attributes.
# Store it in another variable.
obj_dir = dir(m)
# Print the type of the result object.
print(obj_type)
# Print all the attributes (dir) of the result object.
print(obj_dir)

Output:

<class 'object'>
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

An object m is created here.

We used type() in the program to determine the type of the object.

Similarly, we used dir() to retrieve all of the attributes. These attributes (properties and methods) are shared by all Python class instances.

 

Python object() Function with Examples Read More »

Python frozenset() Function with Examples

frozenset() Function in Python:

The frozenset() function returns an immutable frozenset object that has been initialized with elements from the iterable passed in.

A frozen set is nothing more than an immutable version of a Python set object. While elements of a set can be changed at any time, elements of a frozen set do not change after they are created.

As a result, frozen sets can be used as Dictionary keys or as elements of another set. However, it is not ordered in the same way that sets are (the elements can be set at any index).

Syntax:

frozenset(iterable)

Parameters

The frozenset() function only accepts one parameter:

iterable: This is Optional. The iterable contains the elements to be used to initialize the frozenset.

Iterable types include set, dictionary, tuple, and so on.

Return Value:

The frozenset() function returns an immutable frozenset that has been initialized with elements from the specified iterable.

It returns an empty frozenset if no parameters are passed.

Examples:

Example1:

Input:

Given List = ['good', 'morning', 'btechgeeks']

Output:

The Given list's frozenset = frozenset({'morning', 'good', 'btechgeeks'})
An empty frozenset =  frozenset()

Example2:

Input:

Given dictionary = {"hello": 12, "this": 14, "is": 10, "btechgeeks": 20}

Output:

The Given dictionary's frozenset :
frozenset({'btechgeeks', 'is', 'hello', 'this'})

frozenset() Function with Examples in Python

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

Approach:

  • Give the list as static input and store it in a variable.
  • Pass the given list as an argument to the frozenset () function that returns an immutable frozenset object that has been initialized with elements from the iterable passed in.
  • Store it in another variable.
  • Print the frozenset of the given list.
  • Print an empty frozenset without passing any parameters to the frozenset () function.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['good', 'morning', 'btechgeeks']
# Pass the given list as an argument to the frozenset () function that returns
# an immutable frozenset object that has been initialized with elements from
# the iterable passed in.
# Store it in another variable.
rslt = frozenset(gvn_lst)
# Print the frozenset of the given list.
print("The Given list's frozenset =", rslt)
# Print an empty frozenset without passing any parameters to the frozenset ()
# function.
print("An empty frozenset = ", frozenset())

Output:

The Given list's frozenset = frozenset({'morning', 'good', 'btechgeeks'})
An empty frozenset =  frozenset()
Similarly, do the same for the dictionaries

When you use a dictionary as an iterable for a frozen set, the set is created using only dictionary keys.

# Give the dictionary as static input and store it in a variable.
gvn_dict = {"hello": 12, "this": 14, "is": 10, "btechgeeks": 20}
# Pass the given dictionary as an argument to the frozenset () function that returns
# an immutable frozenset object that has been initialized with elements from
# the iterable passed in.
# Store it in another variable.
rslt = frozenset(gvn_dict)
# Print the frozenset of the given dictionary.
print("The Given dictionary's frozenset :")
print(rslt)

Output:

The Given dictionary's frozenset :
frozenset({'btechgeeks', 'is', 'hello', 'this'})
Operations of frozenset

frozenset, like normal sets, can perform operations such as copy, difference, intersection, symmetric difference, and union.

# Give two frozenset's and store them in two separate variables
gvn_froznset1 = frozenset([10, 20, 30, 40])
gvn_froznset2 = frozenset([30, 40, 50, 60])

# copy the given frozenset1 to new variable.
neww = gvn_froznset1.copy()
print(neww)

# Union of frozenset1 and frozenset2
print(gvn_froznset1.union(gvn_froznset2))

# intersection of frozenset1 and frozenset2
print(gvn_froznset1.intersection(gvn_froznset2))

# difference of frozenset1 and frozenset2
print(gvn_froznset1.difference(gvn_froznset2))

# symmetric_difference of frozenset1 and frozenset2
print(gvn_froznset1.symmetric_difference(gvn_froznset2))

Output:

frozenset({40, 10, 20, 30})
frozenset({40, 10, 50, 20, 60, 30})
frozenset({40, 30})
frozenset({10, 20})
frozenset({10, 50, 20, 60})

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

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the given list as an argument to the frozenset () function that returns an immutable frozenset object that has been initialized with elements from the iterable passed in.
  • Store it in another variable.
  • Print the frozenset of the given list.
  • Print an empty frozenset without passing any parameters to the frozenset () function.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Pass the given list as an argument to the frozenset () function that returns
# an immutable frozenset object that has been initialized with elements from
# the iterable passed in.
# Store it in another variable.
rslt = frozenset(gvn_lst)
# Print the frozenset of the given list.
print("The Given list's frozenset =", rslt)
# Print an empty frozenset without passing any parameters to the frozenset ()
# function.
print("An empty frozenset = ", frozenset())

Output:

Enter some random List Elements separated by spaces = 10 40 70 90
The Given list's frozenset = frozenset({40, 10, 90, 70})
An empty frozenset = frozenset()

 

Python frozenset() Function with Examples Read More »

Python vars() Function with Examples

vars() Function in Python:

The vars() function returns an object’s __dict__ attribute.

The __dict__ attribute is a dictionary that contains a list of the object’s changeable attributes.

Note:

It should be noted that calling the vars() function without any parameters will result in the return of a dictionary containing the local symbol table.

Syntax:

vars(object)

Parameters

object: It may be Any object that has the __dict__ attribute.

Return Value:

vars() returns the given object’s __dict__ attribute.

  • If the object passed to vars() does not have the __dict__ attribute, a TypeError exception is thrown.
  • If no arguments are passed to vars(), it behaves similarly to the locals() function.

Note: It should be noted that __dict__ refers to a dictionary or a mapping object. It stores the (writable) attributes of an object.

vars() Function with Examples in Python

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

Approach:

  • Create a class say Employee.
  • Take a variable and initialize it with some random number(eid).
  • Take another variable and initialize it with some random name(ename).
  • Take another variable and initialize it with some random job role(jobrole).
  • Create an object for the above class and apply the vars() method to it.
  • Store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Create a class say, Employee.
class Employee:
    # Take a variable and initialize it with some random number(eid).
    eid = 5
    # Take another variable and initialize it with some random name(ename).
    ename = "kevin"
    # Take another variable and initialize it with some random job role(jobrole).
    jobrole = "software developer"


# Create an object for the above class and apply the vars() method to it
# Store it in a variable.
rslt = vars(Employee)
# Print the above result.
print(rslt)

Output:

{'__module__': '__main__', 'eid': 5, 'ename': 'kevin', 'jobrole': 'software developer', '__dict__': <attribute '__dict__' of 'Employee' objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>, '__doc__': None}

 

Python vars() Function with Examples Read More »