Author name: Vikram Chiluka

How to Create a List and Initialize with Same Values

Python : How to Create a List and Initialize with Same Values

In Python Data Structures, a list is a type of container that is used to store multiple pieces of data at the same time. In Python, unlike Sets, the list is ordered and has a definite count. A list’s elements are indexed in a specific order, and the indexing of a list begins with 0 as the first index.

This article will go over various methods to create a list and Initialize with same values.

Examples:

Input:

size=5 , value="BTechGeeks"

Output:

['BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks']

Make a list and fill it with the same values

There are several ways create a list and initialize with same values some of them are:

Method #1:Using [] and multiply operator

Assume we want to make a list of strings that contains 5 identical strings, such as ‘BTechGeeks’.

You can do the following to initialize a list of immutable items, such as None, strings, tuples, or frozensets, with the same value:

# Function which converts list to string
def createList(size, value):
    # Using multiply operator
    requiredlist = [value]*size
    # return the list
    return requiredlist


# Driver code
# given value and size
size = 5
value = "BTechGeeks"
# passing value and size to createList function
print(createList(size, value))

Output:

['BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks']

[‘BTechGeeks’] will generate a list with a single value, which we can then multiply by 5. It will loop through the contents of the list 5 times.

Note: Never use [e]*n for mutable items. As a result, the list will contain the same object e repeated N times, as well as referencing errors.

Method #2:Using List Comprehension and range()

List comprehension is a simple and compact syntax for creating a list from a string or another list in Python. It’s a quick way to make a new list by performing an operation on each item in the existing one. List comprehension is much faster than using the for loop to process a list.

The for loop in this list comprehension will iterate over the range object 5 times, adding ‘BTechGeeks’ to the list with each iteration.

Below is the implementation:

# Function which converts list to string
def createList(size, value):
    # Using list comprehension and range
    requiredlist = [value for i in range(size)]
    # return the list
    return requiredlist


# Driver code
# given value and size
size = 5
value = "BTechGeeks"
# passing value and size to createList function
print(createList(size, value))

Output:

['BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks']

Method #3: Using itertools repeat() function

The itertools package contains a repeat() function that creates an iterator that returns the object repeatedly. This has the same issue as [e]*n and should be avoided when dealing with mutable items.

Below is the implementation:

#importing itertools
import itertools

# Function which converts list to string
def createList(size, value):
    # Using repeat()
    requiredlist = list(itertools.repeat(value, size))
    # return the list
    return requiredlist


# Driver code
# given value and size
size = 5
value = "BTechGeeks"
# passing value and size to createList function
print(createList(size, value))

Output:

['BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks']

Related Programs:

Python : How to Create a List and Initialize with Same Values Read More »

Convert String to Float Convert String to Float

Python Convert String to Float

In Python, strings are byte sequences that represent Unicode characters. Due to the lack of a character data type in Python, a single character is just a one-length string. To access the string’s components, use square brackets. To generate strings in Python, single quotes, double quotes, and even triple quotes can be used.

This article will go over various methods to convert string to float.

Example:

Input:

'34.124'

Output:

34.124

String to Float Conversion

We’ll look at how to convert a number string to a float object .

Form conversion functions in Python are used to transform one data type to another. The aim of this article is to provide details on how to convert a string to a float. To convert a String to a float in Python, use the float() function.

Float()

Any data form can be converted to a floating-point number using this function.

Syntax:

float(object)

Only one parameter is accepted by the process, and it is also optional to use. The method returns 0.0 if no argument is transmitted.

Parameters:

  • An int, float, or string may be used.
  • If it’s a string, it has to be in the right decimal format.

Return:

  • It gives you a float object as a result.
  • ValueError will be raised if the given string contains something other than a floating-point representation of a number.
  • If no argument is given, 0.0 is returned.
  • Overflow Error is raised if the given statement is beyond the range of float.

Let’s look at some examples of how to convert a string to a float object using the float() function.

Assume we have a Str object with the string ‘34.124′. We’ll transfer the string to the float() function to convert it to a floating-point number, or float entity. Which returns the float object after converting this string to a float. As an example,

# Driver code

# given string value
stringval = '34.124'

# converting string to float
floatvalue = float(stringval)

# printing the float number
print(floatvalue)

# printing the type of the number
print('Type of the number/object :', type(floatvalue))

Output:

34.124
Type of the number/object : <class 'float'>

Convert a comma-separated number string to a float object

Let’s say we have a string called ‘34,123.454’  which includes the number but also some commas. It’s a little difficult to convert this type of string to float. If we transfer this to the float() function directly, we’ll get an error as below:

ValueError: could not convert string to float: '34,123.454'

float() returned an error since string contained characters other than digits. So, before passing the string to the float() function, we need to delete all the extra commas.

We use replace function to replace commas with blank character such that commas  are deleted

Below is the implementation:

# Driver code

# given string value
stringval = '34,123.454'

# convert string with comma to float
# replacing ,(comma) with blank value
floatvalue = float(stringval.replace(',', ''))

# printing the float number
print(floatvalue)

# printing the type of the number
print('Type of the number/object :', type(floatvalue))

Output:

34123.454
Type of the number/object : <class 'float'>

Related Programs:

Python Convert String to Float Read More »

Convert List to String in Python using join() reduce() map()

Convert List to String in Python using join() / reduce() / map()

List:

The list is a type of container in Data Structures in Python that is used to store multiple pieces of data at the same time. In Python, unlike Sets, the list is ordered and has a definite count. The elements in a list are indexed in a definite sequence, and the indexing of a list begins with 0 as the first index.

String:

Strings are sequences of bytes in Python that represent Unicode characters. However, since Python lacks a character data form, a single character is simply a one-length string. Square brackets may be used to access the string’s components. In Python, single quotes, double quotes, and even triple quotes can be used to generate strings.

This article will go over various methods to convert list to string.

Examples:

Input:

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

Output:

this is btech Geeks

List to String conversion

There are several ways to convert list to string some of them are:

Method #1 : Using String Concatenation

The elements of the input list are iterated one by one and added to a new empty string in this process.

As a result, a list is converted to a string.

Below is the implementation:

# Function which converts list to string
def listToString(givenlist):
    # Taking eempty string say string
    string = ""
    # Traverse the list and concate the elements to the string
    for element in givenlist:
        # converting element of list to string and concating to empty string
        # concatenating space to differentiate words(deliminator)
        string = string + str(element) + " "

    # return the final string
    return string


# Driver code
# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks"]

# passing list to convert into string
print(listToString(givenlist))

Output:

hello this is Btech Geeks

Method #2:Using join()

The join() method in Python can be used to convert a List to a String.

Iterables such as Lists, Tuples, Strings, and others are accepted as parameters for the join() process.

It also returns a new string as an argument that contains the elements concatenated from the iterable.

The passed iterable must contain string elements as a prerequisite for the join() method to work.

A TypeError exception is thrown if the iterable includes an integer.

# Function which converts list to string
def listToString(givenlist):
  # using  space " " as separator between the elements of list
    string = ' '.join(givenlist)

    # return the final string
    return string


# Driver code
# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks"]


# passing list to convert into string
print(listToString(givenlist))

Output:

hello this is Btech Geeks

Method #3:Using map()

The map() function in Python can be used to convert a list to a string.

The map() function accepts the function as well as iterable objects like lists, tuples, strings, and so on. Moving on, the map() function uses the provided function to map the elements of the iterable.

General syntax of map:

map(function, iterable)

# Function which converts list to string
def listToString(givenlist):
  # using  space " " as separator between the elements of list
    string = ' '.join(map(str, givenlist))

    # return the final string
    return string


# Driver code
# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks"]


# passing list to convert into string
print(listToString(givenlist))

Output:

hello this is Btech Geeks

The map(str, givenlist) function in the preceding code snippet accepts str function and given list as arguments.

It maps each element of the input iterable( list) to the given function and returns the resultant list of elements.

In addition, the join() method is used to convert the output to string form.

Note: This method also applicable to list of integers since every element is converted to list.

Method #4:Using reduce()

Python’s functools module includes the function reduce(), which takes an iterable sequence as an argument and a function as an argument. This function returns a single value from an iterable sequence of items.

It will generate the value by passing the first two values to the given function argument and then calling the same function again with the result and the next argument. When it has consumed all of the items in order, the final result value will be returned.

Below is the implementation:

import functools
# Function which converts list to string


def listToString(givenlist):
    # deliminator or separator between the elements of list let us say it as space
    deliminator = " "
   
    # using reduce function
    string = functools.reduce(lambda a, b: a + deliminator + b, givenlist)

    # return the final string
    return string


# Driver code
# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks"]


# passing list to convert into string
print(listToString(givenlist))

Output:

hello this is Btech Geeks

We passed two arguments to the reduce() function in this case,

  • A lambda function that takes two arguments and joins them with a delimiter in between.
  • Givenlist

Using the logic provided by the lambda function, it joined all of the elements in the list to form a string.
Related Programs:

Convert List to String in Python using join() / reduce() / map() Read More »

How to Iterate over a List

Python : How to Iterate over a List ?

Lists are similar to dynamically sized arrays, which are declared in other languages(e.g., vector in C++ and ArrayList in Java). Lists do not have to be homogeneous all of the time, which makes it a very useful tool in Python. DataTypes such as Integers, Strings, and Objects can all be included in a single list. Lists are mutable, which means they can be changed after they’ve been created.

We’ll look at a few different ways to iterate through a list in this article.

Examples:

Input:

givenlist=['hello' , 'world' , 'this', 'is' ,'python']

Output:

hello 
world
this 
is 
python

Print the list by iterating through it

There are several ways to iterate through a list some of them are:

Method #1 : Using For loop

We can use for loop to iterate over the list.

Below is the implementation:

# Given list
givenlist=['hello' , 'world' , 'this', 'is' ,'python']

#Using for loop to iterate over the list
for element in givenlist:
    print(element)

Output:

hello 
world
this 
is 
python

Method #2 :Using while loop

In Python, the while loop is used to iterate through a block of code as long as the test expression (condition) is true. This loop is typically used when we don’t know how many times to iterate ahead of time.

Here the condition is loop till length of list

Below is the implementation:

# Given list
givenlist = ['hello', 'world', 'this', 'is', 'python']

# Getting length of list
length = len(givenlist)

# Initializing position to index 0
position = 0

# Iterating using while loop
while position < length:
    print(givenlist[position])
    position = position + 1

Output:

hello 
world
this 
is 
python

Method #3: Using For loop and range() function

If we want to use the standard for loop, which iterates from x to y, we can do so.

Below is the implementation:

# Given list
givenlist = ['hello', 'world', 'this', 'is', 'python']

# Getting length of list
length = len(givenlist)

# Iterating till length of list
for index in range(length):
    print(givenlist[index])

Output:

hello 
world
this 
is 
python

Method #4 : Using list comprehension

We can iterate over the list in one line using list comprehension

Below is the implementation:

# Given list
givenlist = ['hello', 'world', 'this', 'is', 'python']

# Using list comprehension
[print(i) for i in givenlist]

Output:

hello 
world
this 
is 
python

Method #5 :Using enumerate()

The enumerate() function can be used to transform a list into an iterable list of tuples or to get the index based on a condition check.

Below is the implementation:

# Given list
givenlist = ['hello', 'world', 'this', 'is', 'python']

# Using enumerate()
for index, value in enumerate(givenlist):
    print(value)

Output:

hello 
world
this 
is 
python

 
Related Programs:

Python : How to Iterate over a List ? Read More »

Different ways to Iterate over a List in Reverse Order

Python : Different ways to Iterate over a List in Reverse Order

Lists are similar to dynamically sized arrays, which are declared in other languages(e.g., vector in C++ and ArrayList in Java). Lists do not have to be homogeneous all of the time, which makes it a very useful tool in Python. DataTypes such as Integers, Strings, and Objects can all be included in a single list. Lists are mutable, which means they can be changed after they’ve been created.

We’ll look at a few different ways to iterate over a List in Reverse Order in this article.

Example:

Input:

givenlist=['hello' , 'world' , 'this', 'is' ,'python']

Output:

python
is 
this
world
hello

Print list in reverse order

There are several ways to iterate through a list in reverse order some of them are:

Method #1 : Using for loop and range()

When it comes to iterating through something, the loop is always helpful. To iterate in Python, we use the range() function. This approach is known as range ([start], stop[, step]).

start: This is the sequence’s first index.
stop: The range will continue until it reaches this index, but it will not include it.
step: The difference between each sequence element.

range(len(givenlist)-1, -1, -1)

this will return numbers from n to 1 i.e reverse indexes.

In the for loop, use the range() function and the random access operator [] to access elements in reverse.

Below is the implementation:

# Given list
givenlist = ['hello', 'world', 'this', 'is', 'python']

# Iterate over the list in reverse order using for loop and range()

for index in range(len(givenlist) - 1, -1, -1):
    print(givenlist[index])

Output:

python
is 
this
world
hello

Method #2: Using while loop

In Python, the while loop is used to iterate through a block of code as long as the test expression (condition) is true. This loop is typically used when we don’t know how many times to iterate ahead of time.

  • First, we used the len() method to determine the length of the list.
  • The index variable is set to the length of the list -1.
  • It’s used to display the list’s current index when iterating.This loop will continue until the index value reaches 0.
  • The index value is decremented by one each time.
  • The print line will print the list’s current iteration value.

Below is the implementation:

# Given list
givenlist = ['hello', 'world', 'this', 'is', 'python']

# Point position to the last element in list
position = len(givenlist) - 1

# Iterate till 1st element and keep on decrementing position
while position >= 0:
    print(givenlist[position])
    position = position - 1

Output:

python
is 
this
world
hello

Method #3: Using list Comprehension and slicing

givenlist[::-1]

It will generate a temporary reversed list.

Let’s apply this to iterating over the list in reverse in List comprehension.

Below is the implementation:

# Given list
givenlist = ['hello', 'world', 'this', 'is', 'python']

# Using list comprehension and slicing
[print(element) for element in givenlist[::-1]]

Output:

python
is 
this
world
hello

Method #4: Using for loop and reversed()

reversed(givenlist)

The reversed() function returns an iterator that iterates through the given list in reverse order.

Let’s use for loop  to iterate over that reversed sequence.

Below is the implementation:

# Given list
givenlist = ['hello', 'world', 'this', 'is', 'python']

# Using for loop and reversed function
for element in reversed(givenlist):
    print(element)

Output:

python
is 
this
world
hello

Method #5 : Using List Comprehension and reversed() function

reversed(givenlist)

The reversed() function returns an iterator that iterates through the given list in reverse order.

let us use list comprehension to print list in reverse order.

Below is the implementation:

# Given list
givenlist = ['hello', 'world', 'this', 'is', 'python']

# Iterate over the list using List Comprehension and [::-1]
[print(element) for element in reversed(givenlist)]

Output:

python
is 
this
world
hello

Related Programs:

Python : Different ways to Iterate over a List in Reverse Order Read More »

How to Find all Indexes of an Item in a List

Python How to Find all Indexes of an Item in a List

Lists are similar to dynamically sized arrays, which are declared in other languages(e.g., vector in C++ and ArrayList in Java). Lists do not have to be homogeneous all of the time, which makes it a very useful tool in Python. DataTypes such as Integers, Strings, and Objects can all be included in a single list. Lists are mutable, which means they can be changed after they’ve been created.

An index refers to a position within an list.

Given a list and item, the task is to print all indexes of occurrences of that item in the list

Examples:

Input :

givenlist = ["this", "is", "the", "new", "way", "to" , "learn" , "python", "which" , "is" ,"easy" ,"is" ]

item = is

Output:

Indexes are : 1 9 11

Explanation:

Here "is" is present at the indices 1,9 and 11

Print the indices of occurrences of the item

There are several ways to find indices of item in list some of them are:

Method #1: Using For loop and list

Create an empty list. Iterate through each element in the original list using a for-loop.

Append the index of each occurrence of the given item to the empty list.

Below is the implementation:

# Given list
givenlist = ["this", "is", "the", "new", "way", "to", "learn", "python",
             "which", "is", "easy", "is"]

# Given item
item = "is"

# Taking empty list
indexes = []

# Loop over indices of elements in givenlist
for index in range(len(givenlist)):
  # if element is equal to given item then append to empty list
    if givenlist[index] == item:
        indexes.append(index)

# printing the result indexes
print("Indexes are : ", *indexes)

Note : Here * is used to print list with spaces

Output:

Indexes are :  1 9 11

Method #2 : Using enumerate() function

The built-in function enumerate can be used to get the index of all occurrences of an element in a list ().

It was created to solve the loop counter issue and can be used in these type of problems.

Below is the implementation:

# Given list
givenlist = ["this", "is", "the", "new", "way", "to", "learn", "python",
             "which", "is", "easy", "is"]

# Given item
item = "is"

print("Indexes are :", end=" ")

for index, element in enumerate(givenlist):
    # If the element is equal to item then print its index
    if element == item:
        print(index, end=" ")

Output:

Indexes are :  1 9 11

Method #3: Using list comprehension and range

You can get a list of all valid indices with the range() function and then compare the corresponding value

at each index with the given object.

Below is the implementation:

# Given list
givenlist = ["this", "is", "the", "new", "way", "to", "learn", "python",
             "which", "is", "easy", "is"]

# Given item
item = "is"

print("Indexes are :", end=" ")
# Using list comprehension to store indexes in indexes list
indexes = [index for index in range(
    len(givenlist)) if givenlist[index] == item]

# print the list
print(*indexes)

Output:

Indexes are :  1 9 11

Method #4 : Using count() function in itertools

We can use itertools count() function to build an iterator for efficient looping that returns evenly

spaced values beginning with the given amount.

You may use it in conjunction with the zip() function to add sequence numbers as shown below.

from itertools import count
# Given list
givenlist = ["this", "is", "the", "new", "way", "to", "learn", "python",
             "which", "is", "easy", "is"]

# Given item
item = "is"

print("Indexes are :", end=" ")
indexes = [(i, j) for i, j in zip(count(), givenlist) if j == item]


# Traverse the indexes list and print only index
for i in indexes:
    print(i[0], end=" ")

Note: Here we need only index so we print only index element in indexes list

Output:

Indexes are :  1 9 11

Method #5 : Using Numpy

We use numpy.where() function to get indexes of the occurrences of item in given list.

Below is the implementation

import numpy as np
# Given list
givenlist = ["this", "is", "the", "new", "way", "to", "learn", "python",
             "which", "is", "easy", "is"]

# Given item
item = "is"

indexes = np.where(np.array(givenlist) == item)[0]

print("Indexes are :",*indexes)

Output:

Indexes are :  1 9 11

Related Programs:

Python How to Find all Indexes of an Item in a List Read More »

Python hashlib.sha3_256() Function

Python hashlib Module:

To generate a message digest or secure hash from the source message, we can utilize the Python hashlib library.

The hashlib module is required to generate a secure hash message in Python.

The hashlib hashing function in Python takes a variable length of bytes and converts it to a fixed-length sequence. This function only works in one direction. This means that when you hash a message, you obtain a fixed-length sequence. However, those fixed-length sequences do not allow you to obtain the original message.

A hash algorithm is considered better in cryptography if the original message cannot be decoded from the hash message. Changing one byte in the original message also has a big impact(change) on the message digest value.

Python secure hash values are used to store encrypted passwords. So that even the application’s owner does not have access to the user’s password, passwords are matched when the user enters the password again, and the hash value is calculated and compared to the stored value.

Hashing Algorithms That Are Available:

  • The algorithms_available function returns a list of all the algorithms available in the system, including those accessible via OpenSSl. Duplicate algorithm names can also be found.
  • The algorithms in the module can be viewed by using the algorithms_guaranteed function.
import hashlib
# Printing list of all the algorithms
print(hashlib.algorithms_available)
# Viewing algorithms
print(hashlib.algorithms_guaranteed)

Output:

{'sha384', 'blake2s', 'sha3_384', 'sha224', 'md5', 'shake_256', 'blake2b', 'sha3_512', 'sha1', 'shake_128', 'sha512', 'sha3_256', 'sha256', 'sha3_224'}
{'sha384', 'blake2s', 'sha3_384', 'sha224', 'md5', 'shake_256', 'blake2b', 'sha3_512', 'sha1', 'shake_128', 'sha512', 'sha3_256', 'sha256', 'sha3_224'}

Functions:

You only need to know a few functions to use the Python hashlib module.

  • You can hash the entire message at once by using the hashlib.encryption_algorithm_name(b”message”) function.
  • Additionally, the update() function can be used to append a byte message to the secure hash value. The output will be the same in both cases. Finally, the secure hash can be obtained by using the digest() function.
  • It’s worth noting that b is written to the left of the message to be hashed. This b indicates that the string is a byte string.

hashlib.sha3_256() Function:

We can convert a normal string in byte format to an encrypted form using the hashlib.sha3_256() function. Passwords and important files can be hashed to secure them using the hashlib.sha3_256() method.

Syntax:

hashlib.sha3_256()

Return Value:

The hash code for the string given is returned by the sha3_256() function.

Differences

Shortly after the discovery of cost-effective brute force operations against SHA-1, SHA-2 was created. It is a family of two similar hash algorithms, SHA-256 and SHA-512, with varying block sizes.

  • The fundamental distinction between SHA-256 and SHA-512 is word size.
  • SHA-256 uses 32-byte words, whereas SHA-512 employs 64-byte words.
  • Each standard also has modified versions called SHA-224, SHA-384, SHA-512/224, and SHA-512/256. Today, the most often used SHA function is SHA-256, which provides adequate safety at current computer processing capabilities.
  • SHA-384 is a cryptographic hash that belongs to the SHA-2 family. It generates a 384-bit digest of a message.
  • On 64-bit processors, SHA-384 is around 50% faster than SHA-224 and SHA-256, despite having a longer digest. The increased speed is due to the internal computation using 64-bit words, whereas the other two hash algorithms use 32-bit words.
  • For the same reason, SHA-512, SHA-512/224, and SHA-512/256 are faster on 64-bit processors.

Algorithm – digest size (the larger the better):

MD5 –> 128 bits
SHA-1 –> 160 bits
SHA-256 –> 256 bits
SHA-512 –> 512 bits

hashlib.sha3_256() Function in Python

Method #1: Using sha3_256() Function (Static Input)

Here, we encrypt the byte string or passwords to secure them using the hashlib.sha3_256() function.

Approach:

  • Import hashlib module using the import keyword
  • Create a reference/Instance variable(Object) for the hashlib module and call sha3_256() function and store it in a variable
  • Give the string as static input(here b represents byte string) and store it in another variable.
  • Call the update() function using the above-created object by passing the above-given string as an argument to it
  • Here it converts the given string in byte format to an encrypted form.
  • Get the secure hash using the digest() function.
  • The Exit of the Program.

Below is the implementation:

# Import hashlib module using the import keyword
import hashlib

# Creating a reference/Instance variable(Object) for the hashlib module and 
# call sha3_256() function and store it in a variable
obj = hashlib.sha3_256()

# Give the string as static input(here b represents byte string) and store it in another variable.
gvn_str = b'Python-programs'

# Call the update() function using the above created object by passing the above given string as 
# an argument to it
# Here it converts the given string in byte format to an encrypted form.
obj.update(gvn_str)
# Get the secure hash using the digest() function.
print(obj.digest())

Output:

b'\xf7\x97[\xc6b{ua\x90bn\xbb\xf54\xc4$\xab\x08\xde\xe6\x11\xb3\xd3\xca\x99_\x89\x0b\xa99>\x9c'

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

Approach:

  • Import hashlib module using the import keyword
  • Create a reference/Instance variable(Object) for the hashlib module and call sha3_256() function and store it in a variable
  • Give the string as user input using the input() function and store it in another variable.
  • Convert the given string into a byte string using the bytes() function by passing the given string, ‘utf-8’ as arguments to it.
  • Call the update() function using the above-created object by passing the above-given string as an argument to it
  • Here it converts the given string in byte format to an encrypted form.
  • Get the secure hash using the digest() function.
  • The Exit of the Program.

Below is the implementation:

# Import hashlib module using the import keyword
import hashlib

# Creating a reference/Instance variable(Object) for the hashlib module and 
# call sha3_256() function and store it in a variable
obj = hashlib.sha3_256()

# Give the string as user input using the input() function and store it in another variable.
gvn_str = input("Enter some random string = ")
# Convert the given string into byte string using the bytes() function by passing given string, 
# 'utf-8' as arguments to it 
gvn_str=bytes(gvn_str, 'utf-8')

# Call the update() function using the above created object by passing the above given string as 
# an argument to it
# Here it converts the given string in byte format to an encrypted form.
obj.update(gvn_str)
# Get the secure hash using the digest() function.
print(obj.digest())

Output:

Enter some random string = welcome to Python-programs
b'\xd2\xd5!\xb3\xe4\xfaM\x93</8#\xf7\xa1\xdb\xces\nE^\xc1\xb2ukW\x8eF\x8e\xa0y\x8c\x05'

Python hashlib.sha3_256() Function Read More »

Python hashlib.sha3_384() Function

Python hashlib Module:

To generate a message digest or secure hash from the source message, we can utilize the Python hashlib library.

The hashlib module is required to generate a secure hash message in Python.

The hashlib hashing function in Python takes a variable length of bytes and converts it to a fixed-length sequence. This function only works in one direction. This means that when you hash a message, you obtain a fixed-length sequence. However, those fixed-length sequences do not allow you to obtain the original message.

A hash algorithm is considered better in cryptography if the original message cannot be decoded from the hash message. Changing one byte in the original message also has a big impact(change) on the message digest value.

Python secure hash values are used to store encrypted passwords. So that even the application’s owner does not have access to the user’s password, passwords are matched when the user enters the password again, and the hash value is calculated and compared to the stored value.

Hashing Algorithms That Are Available:

  • The algorithms_available function returns a list of all the algorithms available in the system, including those accessible via OpenSSl. Duplicate algorithm names can also be found.
  • The algorithms in the module can be viewed by using the algorithms_guaranteed function.
import hashlib
# Printing list of all the algorithms
print(hashlib.algorithms_available)
# Viewing algorithms
print(hashlib.algorithms_guaranteed)

Output:

{'sha384', 'blake2s', 'sha3_384', 'sha224', 'md5', 'shake_256', 'blake2b', 'sha3_512', 'sha1', 'shake_128', 'sha512', 'sha3_256', 'sha256', 'sha3_224'}
{'sha384', 'blake2s', 'sha3_384', 'sha224', 'md5', 'shake_256', 'blake2b', 'sha3_512', 'sha1', 'shake_128', 'sha512', 'sha3_256', 'sha256', 'sha3_224'}

Functions:

You only need to know a few functions to use the Python hashlib module.

  • You can hash the entire message at once by using the hashlib.encryption_algorithm_name(b”message”) function.
  • Additionally, the update() function can be used to append a byte message to the secure hash value. The output will be the same in both cases. Finally, the secure hash can be obtained by using the digest() function.
  • It’s worth noting that b is written to the left of the message to be hashed. This b indicates that the string is a byte string.

hashlib.sha3_384() Function:

We can convert a normal string in byte format to an encrypted form using the hashlib.sha3_384() function. Passwords and important files can be hashed to secure them using the hashlib.sha3_384() method.

Syntax:

hashlib.sha3_384()

Return Value:

The hash code for the string given is returned by the sha3_384() function.

Differences

Shortly after the discovery of cost-effective brute force operations against SHA-1, SHA-2 was created. It is a family of two similar hash algorithms, SHA-256 and SHA-512, with varying block sizes.

  • The fundamental distinction between SHA-256 and SHA-512 is word size.
  • SHA-256 uses 32-byte words, whereas SHA-512 employs 64-byte words.
  • Each standard also has modified versions called SHA-224, SHA-384, SHA-512/224, and SHA-512/256. Today, the most often used SHA function is SHA-256, which provides adequate safety at current computer processing capabilities.
  • SHA-384 is a cryptographic hash that belongs to the SHA-2 family. It generates a 384-bit digest of a message.
  • On 64-bit processors, SHA-384 is around 50% faster than SHA-224 and SHA-256, despite having a longer digest. The increased speed is due to the internal computation using 64-bit words, whereas the other two hash algorithms use 32-bit words.
  • For the same reason, SHA-512, SHA-512/224, and SHA-512/256 are faster on 64-bit processors.

Algorithm – digest size (the larger the better):

MD5 –> 128 bits
SHA-1 –> 160 bits
SHA-256 –> 256 bits
SHA-512 –> 512 bits

hashlib.sha3_384() Function in Python

Method #1: Using sha3_384() Function (Static Input)

Here, we encrypt the byte string or passwords to secure them using the hashlib.sha3_384() function.

Approach:

  • Import hashlib module using the import keyword
  • Create a reference/Instance variable(Object) for the hashlib module and call sha3_384() function and store it in a variable
  • Give the string as static input(here b represents byte string) and store it in another variable.
  • Call the update() function using the above-created object by passing the above-given string as an argument to it
  • Here it converts the given string in byte format to an encrypted form.
  • Get the secure hash using the digest() function.
  • The Exit of the Program.

Below is the implementation:

# Import hashlib module using the import keyword
import hashlib

# Creating a reference/Instance variable(Object) for the hashlib module and 
# call sha3_384() function and store it in a variable
obj = hashlib.sha3_384()

# Give the string as static input(here b represents byte string) and store it in another variable.
gvn_str = b'Python-programs'

# Call the update() function using the above created object by passing the above given string as 
# an argument to it
# Here it converts the given string in byte format to an encrypted form.
obj.update(gvn_str)
# Get the secure hash using the digest() function.
print(obj.digest())

Output:

b'\xf5;.\x1f\xb3$\xfd\xc2s7\xa5\x13\xa9\xc9\xceB\xd1A,u\x7fy\xeaw\xab\x07\x0b,lN\xefg\x86\x04t\xb0~\xd9\xe4_\xed\xc2\x07\xdb\xad$\xf4\xea'

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

Approach:

  • Import hashlib module using the import keyword
  • Create a reference/Instance variable(Object) for the hashlib module and call sha3_384() function and store it in a variable
  • Give the string as user input using the input() function and store it in another variable.
  • Convert the given string into a byte string using the bytes() function by passing the given string, ‘utf-8’ as arguments to it.
  • Call the update() function using the above-created object by passing the above-given string as an argument to it
  • Here it converts the given string in byte format to an encrypted form.
  • Get the secure hash using the digest() function.
  • The Exit of the Program.

Below is the implementation:

# Import hashlib module using the import keyword
import hashlib

# Creating a reference/Instance variable(Object) for the hashlib module and 
# call sha3_384() function and store it in a variable
obj = hashlib.sha3_384()

# Give the string as user input using the input() function and store it in another variable.
gvn_str = input("Enter some random string = ")
# Convert the given string into byte string using the bytes() function by passing given string, 
# 'utf-8' as arguments to it 
gvn_str=bytes(gvn_str, 'utf-8')

# Call the update() function using the above created object by passing the above given string as 
# an argument to it
# Here it converts the given string in byte format to an encrypted form.
obj.update(gvn_str)
# Get the secure hash using the digest() function.
print(obj.digest())

Output:

Enter some random string = welcome to Python-programs
b'\xe4\xf2\xe03\xcbG\xe5YH.\xe2\x13W\xbc\xd0pQ\xd4dYshc=\xdc\xeeY\xf9\xa5dX\xda\x8c\x08\x18\xa1\xe4,\xe6z\x99x\xf2\xa4l\xe4\xc4$'

Python hashlib.sha3_384() Function Read More »

Python Numpy matrix.nonzero() Function

NumPy Library 

NumPy is a library in python that is created to work efficiently with arrays in python. It is fast, easy to learn, and provides efficient storage. It also provides a better way of handling data for the process. We can create an n-dimensional array in NumPy. To use NumPy simply have to import it into our program and then we can easily use the functionality of NumPy in our program.

NumPy is a Python library that is frequently used for scientific and statistical analysis. NumPy arrays are grids of the same datatype’s values.

Numpy matrix.nonzero() Function:

we can obtain the index value of a nonzero value from a specified matrix using the matrix.nonzero() function of the NumPy module. It always returns a two-dimensional array.

Syntax:

 matrix.nonzero()

Return Value:

The index value of the nonzero value from the given matrix is returned by the nonzero() function.

Numpy matrix.nonzero() Function in Python

For 2-Dimensional (2D) Matrix

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing some random 2D matrix as an argument to it and store it in a variable
  • Apply nonzero() function on the given matrix to get the index values of nonzero elements from the given matrix.
  • Store it in another variable
  • Print the index values of nonzero elements from the given matrix.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing 
# some random 2D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[2, 0; 6, 3]')
            
# Apply nonzero() function on the given matrix to get the index values of nonzero elements from the given matrix
# Store it in another variable
rslt = gvn_matrx.nonzero()
# Print the index values of nonzero elements from the given matrix
print("The index values of nonzero elements from the given matrix:")
print(rslt)

Output:

The index values of nonzero elements from the given matrix:
(array([0, 1, 1]), array([0, 0, 1]))

For 3-Dimensional (3D) Matrix

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing some random 3D matrix as an argument to it and store it in a variable
  • Apply nonzero() function on the given matrix to get the index values of nonzero elements from the given matrix.
  • Store it in another variable
  • Print the index values of nonzero elements from the given matrix.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing 
# some random 3D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[0, 4, 1; 8, 0, 3; 0, 9, 5]')
            
# Apply nonzero() function on the given matrix to get the index values of nonzero elements from the given matrix
# Store it in another variable
rslt = gvn_matrx.nonzero()
# Print the index values of nonzero elements from the given matrix
print("The index values of nonzero elements from the given matrix:")
print(rslt)

Output:

The index values of nonzero elements from the given matrix:
(array([0, 0, 1, 1, 2, 2]), array([1, 2, 0, 2, 1, 2]))

Python Numpy matrix.nonzero() Function Read More »

Python Numpy matrix.partition() Function

NumPy Library 

NumPy is a library in python that is created to work efficiently with arrays in python. It is fast, easy to learn, and provides efficient storage. It also provides a better way of handling data for the process. We can create an n-dimensional array in NumPy. To use NumPy simply have to import it into our program and then we can easily use the functionality of NumPy in our program.

NumPy is a Python library that is frequently used for scientific and statistical analysis. NumPy arrays are grids of the same datatype’s values.

Numpy matrix.partition() Function:

Using the matrix.partition() method of the Numpy module, we can partition the matrix in such a manner that the index value that we pass sorts the matrix in such a way that all the values smaller than that value are moved to the left, and others are moved to the right.

Syntax:

 matrix.partition(index)

Return Value:

The partitioned matrix is returned by the partition() function.

Numpy matrix.partition() Function in Python

For 1-Dimensional (1D) Matrix(array)

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(1-Dimensional) using the matrix() function of numpy module by passing some random 1D matrix as an argument to it and store it in a variable
  • Print the given matrix
  • Apply partition() function on the given matrix by passing some random index value as an argument to it to partition the given matrix.
  • Here index value = 3, and the value at that 3rd index is 4. The values less than 4 (i.e, 1,2) are moved to the left, and others (6) are moved to the right.
  • Print the given matrix after partition.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(1-Dimensional) using the matrix() function of numpy module by passing 
# some random 1D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[2, 1, 6, 4]')
# Print the given matrix
print("The given matrix is:") 
print(gvn_matrx)   

# Apply partition() function on the given matrix by passing some random index value as an argument to it
# to partition the given matrix.
# Here index value = 3, the value at the 3rd index is 4. The values less than 4 (i.e, 1,2) are 
# moved to the left and others (6) are moved to the right
gvn_matrx.partition(3)
# Print the given matrix after partition.
print("The given matrix after partition is:")
print(gvn_matrx)

Output:

The given matrix is:
[[2 1 6 4]]
The given matrix after partition is:
[[1 2 4 6]]

Explanation:

Here index value = 3, the value at the 3rd index is 4. 
The values less than 4 (i.e, 1 and 2) are moved to the left and 
other number 6 is moved to the right

For 2-Dimensional (2D) Matrix

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing some random 2D matrix as an argument to it and store it in a variable
  • Print the given matrix
  • Apply partition() function on the given matrix by passing some random index value as an argument to it to partition the given matrix.
  • Print the given matrix after partition.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing 
# some random 2D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[10, 1; 2, 7]')
# Print the given matrix
print("The given matrix is:") 
print(gvn_matrx)   

# Apply partition() function on the given matrix by passing some random index value as an argument to it
# to partition the given matrix.
gvn_matrx.partition(1)
# Print the given matrix after partition.
print("The given matrix after partition is:")
print(gvn_matrx)

Output:

The given matrix is:
[[10 1]
 [ 2 7]]
The given matrix after partition is:
[[ 1 10]
 [ 2 7]]

Python Numpy matrix.partition() Function Read More »