Python

Remove First N Characters from String in Python

Strings are one of the most commonly used types in Python. We can easily make them by enclosing characters in quotes. Python considers single quotes to be the same as double quotes. String creation is as easy as assigning a value to a variable.

Given a string, the task is to remove first n characters from string.

Examples:

Input:

string="BTechGeeks" n=3

Output:

chGeeks

Remove First N Characters from String

There are several ways to remove first n characters from string some of them are:

Method #1:Using slicing

It returns the characters of the string as a new string from index position start to end -1. The default values for start and end are 0 and Z, where Z is the length of the string. If neither start nor end are specified, it selects all characters in the string, from 0 to size-1, and creates a new string from those characters.

This slicing technique can be used to cut out a piece of string that includes all characters except the first N characters.

Below is the implementation:

# function which removes first n characters of string
def removeFirstN(string, n):
    # removing first n characters of string
    string = string[n:]
    # return the string
    return string


# given string
string = "BTechGeeks"
# given n
n = 3
# passing string and n to removeFirstN function
print(removeFirstN(string, n))

Output:

chGeeks

Method #2 : Using for loop

To delete the first N characters from a string, we can iterate through the string’s characters one by one, selecting all characters from index position N until the end of the string.

Below is the implementation:

# function which removes first n characters of string
def removeFirstN(string, n):
    # taking a empty string
    newstr = ""
    # removing first n characters of string using for loop
    # Traverse the string from n to end
    for i in range(n, len(string)):
        newstr = newstr+string[i]

    # return the string
    return newstr


# given string
string = "BTechGeeks"
# given n
n = 3
# passing string and n to removeFirstN function
print(removeFirstN(string, n))

Output:

chGeeks

Method #3 :Using regex to remove first two characters

In Python, we can use regex to match two groups in a string, i.e.

Group 1: The first N characters in a string
Group 2 consists of every character in the string except the first N characters.
The string is then modified by replacing both groups with a single group, group 2.

Below is the implementation:

import re
def removeGroup(k):
    # Only group 1 should be returned from the match object.
        # Other groups should be deleted.
    return k.group(2)
# given string
string = "BTechGeeks"
result = re.sub("(^.{2})(.*)", removeGroup, string)
print(result)

Output:

echGeeks

Related Programs:

Remove First N Characters from String in Python Read More »

Remove Last N Characters from String in Python

Strings are one of the most commonly used types in Python. We can easily make them by enclosing characters in quotes. Python considers single quotes to be the same as double quotes. String creation is as easy as assigning a value to a variable.

Given a string, the task is to remove last n characters from string.

Examples:

Input:

string="BTechGeeks" n=3

Output:

BTechGe

Remove Last N Characters from String

There are several ways to remove last n characters from string some of them are:

Method #1:Using slicing

It returns the characters of the string as a new string from index position start to end -1. The default values for start and end are 0 and Z, where Z is the length of the string. If neither start nor end are specified, it selects all characters in the string, from 0 to size-1, and creates a new string from those characters.

This slicing technique can be used to cut out a piece of string that includes all characters except the last N characters.

Below is the implementation:

# function which removes last n characters of string
def removeLastN(string, n):
    # calculate the size of string
    size = len(string)
    # removing last n characters of string
    string = string[:size-n]
    # return the string
    return string


# given string
string = "BTechGeeks"
# given n
n = 3
# passing string and n to removeLastN function
print(removeLastN(string, n))

Output:

BTechGe

Method #2 : Using for loop

To delete the last N characters from a string, we can iterate through the string’s characters one by one, selecting all characters from index position 0 until the size – n of the string.

Below is the implementation:

# function which removes last n characters of string
def removeLastN(string, n):
    # taking a empty string
    newstr = ""
    # removing last n characters of string using for loop
    # Traverse the string from 0 to sizr-n
    for i in range(0, len(string)-n):
        newstr = newstr+string[i]

    # return the string
    return newstr


# given string
string = "BTechGeeks"
# given n
n = 3
# passing string and n to removelastN function
print(removeLastN(string, n))

Output:

BTechGe

Method #3 :Using regex to remove last two characters

In Python, we can use regex to match two groups in a string, i.e.

Group 1: The first N characters in a string
Group 2 consists of every character in the string except the first N characters.
The string is then modified by replacing both groups with a single group, group 1.

Below is the implementation:

import re

def removeGroup(k):
    # Only group 1 should be returned from the match object.
        # Other groups should be deleted.
    return k.group(1)

# given string
string = "BTechGeeks"
result = re.sub("(.*)(.{2}$)", removeGroup, string)
print(result)

Output:

BTechGee

 
Related Programs:

Remove Last N Characters from String in Python Read More »

Python: Remove All Elements from Set using Clear()/Difference_Update()/Discard()

Python set is a list of items that are not ordered. – Each element in the set must be unique and immutable, and duplicate elements are removed from the sets. Sets are mutable, which means they can be changed after they have been created.

The elements of the set, unlike other Python sets, do not have an index, which means we cannot access any element of the set directly using the index. To get the list of elements, we can either print them all at once or loop through the collection.

Examples:

Input:

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

Output:

set()

Delete all the elements from the set

There are several ways to remove all the elements 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.

Approach:

  • While iterating over a set, we cannot modify it.
  • So We will make a list of the set’s elements, then iterate through that list, removing each element from the set.

Below is the implementation:

# given set
givenset = {'this', 'is', 'BTechGeeks'}

# using for loop to traverse the set
for element in list(givenset):
    # remove that element from set
    givenset.discard(element)
# print the set
print(givenset)

Output:

set()

Method #2:Using clear() function

The clear() method clears the set of all elements.

syntax:

given_set.clear()

parameters:

The clear() method accepts no parameters.

Return :

The clear() method does not return a value.

Below is the implementation:

# given set
givenset = {'this', 'is', 'BTechGeeks'}

# using clear()
givenset.clear()
# print the set
print(givenset)

Output:

set()

Method #3:Using difference_update() method

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 us use this method to remove all the elements from the set

We can pass given set as parameter for the difference_update() function

Below is the implementation:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# using difference_update()
givenset.difference_update(givenset)
# print the set
print(givenset)

Output:

set()

Related Programs:

Python: Remove All Elements from Set using Clear()/Difference_Update()/Discard() Read More »

Python : How to Insert an element at specific index in 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 the task is to insert an element at specific index in given list.

Insert an element at Specific Index in List

1)Insert() function

Syntax:

givenlist.insert(index, element)

Parameters:

index - the position in the array at which the element must be inserted.
element - the element that will be added to the list.

Return:

This method does not return a value, but instead inserts the specified element at the specified index.

2)Inserting an element at a specific position

Suppose we want to insert ‘python’ in a givenlist at index 3 we can pass arguments like

insert(3,value) where value=‘python’

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BTechGeeks']
# given value
value = 'python'
# given index
index = 3
# inserting the given value at given index
givenlist.insert(index, value)
# print the list
print(givenlist)

Output:

['hello', 'this', 'is', 'python', 'BTechGeeks']

3)Inserting element at the first position of the list

We know that the starting index of list is 0 so we give 0 as index while inserting the given value.

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BTechGeeks']
# given value
value = 'python'
# inserting the given value at starting position
givenlist.insert(0, value)
# print the list
print(givenlist)

Output:

['python', 'hello', 'this', 'is', 'BTechGeeks']

4)Inserting element at the end position of the list

We know that the last index of the list is len(list)-1 to insert element at end we use len(list) as parameter.

Passing this index to insert function inserts the element at the end of the list.

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BTechGeeks']
# given value
value = 'python'
# inserting the given value at end position
givenlist.insert(len(givenlist), value)
# print the list
print(givenlist)

Output:

['hello', 'this', 'is', 'BTechGeeks', 'python']

5)Insert all elements of second list at specific index in given list

By slicing we can insert it easily .

Splice given list from 0 to index-1 and merge all of list2’s elements into it. Then, from index to the end of the list, merge all of the remaining elements.

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BTechGeeks']
# given value
givenlist2 = ['welcome', 'to', 'python']
# given index
index = 2
# inserting the given value using slicing
givenlist = givenlist[:index]+givenlist2+givenlist[index:]
# print the list
print(givenlist)

Output:

['hello', 'this', 'welcome', 'to', 'python', 'is', 'BTechGeeks']

Related Programs:

Python : How to Insert an element at specific index in List ? Read More »

Python Dictionary: Pop() Function and Examples

Dictionaries are the implementation by Python of a data structure associative array. A dictionary is a collection of pairs of key values. A key pair and its associated value represent each key pair.

The list of key value pairs in curly braces that is separated by comma defines a dictionary. Column ‘:’ separates the value of each key.

A dictionary cannot be sorted only to get a representation of the sorted dictionary. Inherently, dictionaries are orderless, but not other types, including lists and tuples. Therefore, you need an ordered data type, which is a list—probably a list of tuples.

Pop() was defined in the Python language for almost all containers, including list, set, and so on. This article will demonstrate the pop() method provided by Python dictionaries. This method is useful for programmers who frequently use the dictionary.

Pop Function in Python Dictionary with Examples

1)pop() function

Syntax:

dictionary.pop(key,default)

Parameters:

key: The key for which the key-value pair must be returned and removed.
Default value :If the specified key is not present, the default value is returned.

Return:

If key is present, returns the value associated with the deleted key-value pair.
If no key is specified, the default value is used.
If the key is not present and the default value is not specified, a KeyError is returned.

2)Removing a key-value pair from dictionary using pop()

Assume we have a dictionary with keys of strings and values of integers. Now we want to remove an entry from the dictionary with the key ‘this’. We can implement this as below.

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# given key which should be removed
givenkey = 'this'
# printing the dictionary before modification
print("Before Modification", dictionary)
# removing 'this' key from dictionary
# storing its value in value function
keyvalue = dictionary.pop(givenkey)
# printing the value
print("Value of key :", keyvalue)
# printing the dictionary after modification
print("After Modification", dictionary)

Output:

Before Modification {'this': 200, 'is': 100, 'BTechGeeks': 300}
Value of key : 200
After Modification {'is': 100, 'BTechGeeks': 300}

3)Removing the key which doesn’t exist in given dictionary(with default value)

If we attempt to remove a key from the dictionary that does not exist. The default value will then be returned by the pop() function.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# given key which should be removed
givenkey = 'hello'
# printing the dictionary before modification
print("Before Modification", dictionary)
# removing 'this' key from dictionary
# storing its value in value function
keyvalue = dictionary.pop(givenkey, 500)
# printing the value
print("Value of key :", keyvalue)
# printing the dictionary after modification
print("After Modification", dictionary)

Output:

Before Modification {'this': 200, 'is': 100, 'BTechGeeks': 300}
Value of key : 500
After Modification {'this': 200, 'is': 100, 'BTechGeeks': 300}

4)Removing the key which doesn’t exist in given dictionary(without default value)

When we use the pop() function, we try to remove a key from the dictionary that does not exist, and we do not pass the default value. The pop() function will then throw a KeyError.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# given key which should be removed
givenkey = 'hello'
# printing the dictionary before modification
print("Before Modification", dictionary)
# removing 'this' key from dictionary
# storing its value in value function
keyvalue = dictionary.pop(givenkey)
# printing the value
print("Value of key :", keyvalue)
# printing the dictionary after modification
print("After Modification", dictionary)

Output:

Traceback (most recent call last):
  File "/home/bbdc799e66bc794f9534237294f5b64c.py", line 9, in <module>
    keyvalue = dictionary.pop(givenkey)
KeyError: 'hello'

Related Programs:

Python Dictionary: Pop() Function and Examples Read More »

Python: Iterate Over Dictionary with Index

Dictionaries are the implementation by Python of a knowledge structure associative array. A dictionary is a collection of pairs of key values. A key pair and its associated value represent each key pair.
The list of key value pairs in curly braces that’s separated by comma defines a dictionary. Column ‘:’ separates the value of each key.
A dictionary can’t be sorted only to urge a representation of the sorted dictionary. Inherently, dictionaries are orderless, but not other types, including lists and tuples. Therefore, you would like an ordered data type, which may be a list—probably an inventory of tuples.

Examples:

Input :

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

Output:

index = 0  ; key = this  ; Value = 200
index = 1  ; key = is  ; Value = 100
index = 2  ; key = BTechGeeks  ; Value = 300

Traverse the Dictionary with Index

1)Enumerate() function:

When working with iterators, we frequently encounter the need to keep track of the number of iterations. Python makes it easier for programmers by providing a built-in function enumerate() for this purpose.
Enumerate() adds a counter to an iterable and returns it as an enumerate object. This enumerate object can then be utilized in for loops directly or converted into an inventory of tuples using the list() method.

Syntax:

enumerate(iterable, start=0)

Parameters:

iterable:  an iterator, a sequence, or objects that support iteration

start :   the index value from which the counter will be started; the default value is 0.

Return:

The method enumerate() adds a counter to an iterable and returns it. The object returned is an enumerate object.

2)Traverse over all key-value pairs of given dictionary by index

We can traverse over the dictionary by passing given dictionary as parameter in enumerate() function

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# Traverse all key-value pairs of given dictionary by index
for i, key in enumerate(dictionary):
    print('index =', i, ' ; key =', key, ' ; Value =', dictionary[key])

Output:

index = 0  ; key = this  ; Value = 200
index = 1  ; key = is  ; Value = 100
index = 2  ; key = BTechGeeks  ; Value = 300

3)Traverse over all keys of given dictionary by index

The dictionary class’s keys() function returns an iterable sequence of all the dictionary’s keys. We can pass that to the enumerate() function, which will return keys as well as index position.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# Traverse all keys of given dictionary by index
for i, key in enumerate(dictionary.keys()):
    print('index =', i, ' ; key =', key)

Output:

index = 0  ; key = this
index = 1  ; key = is
index = 2  ; key = BTechGeeks

4)Traverse over all values of given dictionary by index

The dictionary class’s values() function returns an iterable sequence of all the dictionary’s values. We can pass that to the enumerate() function, which will return values as well as index position.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# Traverse all values of given dictionary by index
for i, value in enumerate(dictionary.values()):
    print('index =', i, ' ; value =', value)

Output:

index = 0  ; value = 200
index = 1  ; value = 100
index = 2  ; value = 300

Related Programs:

Python: Iterate Over Dictionary with Index Read More »

Python Programming – Basic Operations

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

Python Programming – Basic Operations

Basic Operations

Arithmetic operations when applied on NumPy arrays, they are implemented element-wise.

>>> a=np . array ( [ 20 , 30 , 40 , 50 ] )
>>> b=np . arange ( 4 ) 
>>> c=a - b 
>>> c
array ( [ 20 , 29 , 38 , 47 ] )
>>> b**2
array ( [ 0 , 1 , 4 , 9 ] )
>>> a<39
array ( [ True , True , False , False ] , dtype=bool )

The product operator * operates element-wise in NumPy arrays. The matrix product can be performed using the dot ( ) function or creating matrix objects (refer section 7.8).

>>> a=np . array ( [ [ 1 , 1 ] ,
. . . [ 0 , 1 ] ] )
>>> b=np . array ( [ [ 2 , 0 ] ,
. . . [ 3 , 4 ] ] )
>>> a*b 
array ( [ [ 2 , 0 ] ,
[ 0 , 4 ] ] )
>>> np . dot ( a , b ) 
array ( [ [ 5 , 4 ] ,
[ 3 , 4 ] ] )

Some operations, such as +=, *=, etc., modifies an existing array, rather than creating a new array.

>>> a=np . array ( [ [ 1 , 2 ] ,                        # a is integer type
. . . [ 3 , 4 ] ] )
>>> b=np . array ( [ [ 1 . , 2 . ] ,                   # b is float type
. . . [ 3 . , 4 . ] ] )
>>> a*=2 
>>> a
array ( [ [ 2 , 4 ] ,
[ 6 , 8 ] ] )
>>> b+=a 
>>> b
array ( [ [ 3 . , 6 . ] ,
[ 9 . , 12 . ] ] )
>>> a+=b                                                  # b is converted to integer type
>>> a
array ( [ [ 5 , 10 ] ,
[ 15 , 20 ] ] )

When operating with arrays of different types, the type of the resulting array corresponds to the more general or precise one (a behavior known as “upcasting”).

>>> a=np . array ( [ 1 . 1 , 2 . 2 , 3 . 3 ] )
>>> a . dtype . name
' float64 ' 
>>> b=np . array ( [ 4 , 5 , 6 ] )
>>> b . dtype . name ' int32 '
>>> c=a+b 
>>> c
array 0( [ 5 . 1 , 7 . 2 , 9 . 3 ] )
>>> c . dtype . name ' float64 '

Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class .

>>> a=np . array ( [ [5 , 8 ] ,
. . . [ 3 , 6 ] ] )
>>> a . sum ( )
22
>>> a . min ( )
3
>>> a . max ( )
8

By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array:

>>> a=np . arange ( 12 ) . reshape ( 3 , 4 )
>>> a
array ( [ [ 0 , 1 , 2 , 3 ] ,
[ 4 , 5 , 6 , 7 ] ,
[ 8 , 9 , 10 , 11 ] ] )
>>> a.sum(axis=0)                                             # Sum of each column
array ( [12, 15, 18, 21] )
>>> a.min(axis=1)                                             # Minimum of each now
array ( [ 0 , 4 , 8 ] )
>>> a . cumsum ( axis=1 )                                  # Cumulative sum along each now
array ( [ [ 0 , 1 , 3 , 6 ] ,
[ 4 , 9 , 15 , 22 ] ,
[ 8 , 17 , 27 , 38 ] ] )

Python Programming – Basic Operations Read More »

Python Programming – NumPy Array

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

Python Programming – NumPy Array

NumPy array

NumPy’s main object is the homogeneous multi-dimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In NumPy, array dimensions are called “axes”, and the number of axes is known as “rank”. For example, the coordinates of a point in 3D space [ 1, 2, 1 ] is an array of rank 1, because it has one axis and that axis has a length of 3. In the following example, the array has rank 2 (it is two-dimensional). The first dimension (axis) has a length of 2, the second dimension has a length of 3.

[ [ 1 . , 0 . , 0 . ] , 
[ 0 . , 1 . , 2 . ] ]

Some of the attributes of an ndarray object are:

ndarray . ndim
The number of axes (dimensions) or rank of the array.

ndarray . shape
The dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For an array of n rows and m columns, shape will be (n, m). The length of the shape tuple is therefore the rank ndim.

ndarray.size
The total number of elements of the array. This is equal to the product of the elements of shape.

ndarray.dtype
An object describing the type of the elements in the array. One can create or specify dtype using standard Python type. Additionally, NumPy provides types of its own, numpy.int32, numpy. intl6, and numpy. f loat64 are some examples.

ndarray.itemsize
The size in bytes of each element of the array. For example, an array of elements of type float 6 4 has itemsize as 8 (=64/8), while one of type complex32 has itemsize as 4 (=32/8). It is equivalent to ndarray. dtype . itemsize.’

 

>>> import numpy as np
>>> a=np . array ( [ [ 0 , 1 , 2 , 3 , 4 ] ,
. . .                           [ 5 , 6 , 7 , 8 , 9 ] , 
. . .                           [ 10 , 11 , 12 , 13 , 14 ] ] )
. . . 
>>> type ( a )
<type ' numpy . ndarray ' > 
>>> a . shape 
( 3 , 5 )
>>> a . ndim 
2
>>> a.dtype 
dtype ( ' int32 ' )
>>> a . dtype . name
' int32 '
>>> a.itemsize 
4
>>> a . size 
15

Array creation

There are several ways to create NumPy array, one approach is from a regular Python list or tuple using the array () method. The type of the resulting array is deduced from the type of the elements in the sequences.

>>> import numpy as np 
>>> a=np.array ( [ 1 , 2 , 3 ] )
>>> a . dtype 
dtype ( ' int32 ' )
>>> b=np . array ( ( 1 . 2 , 3 . 4 , 5 . 6 ) )
>>> b. dtype 
dtype ( ' float64 ' )

A frequent error consists in calling array ( ) with multiple numeric arguments, rather than providing a single list or tuple of numbers as an argument.

>>> a=np . array ( 1 , 2 , 3 , 4 )      # WRONG
>>> a=np . array ( [ 1 , 2 , 3 , 4] )  # RIGHT

array ( ) transforms sequence of sequences into two-dimensional arrays, sequences of sequences of sequences into three-dimensional arrays, and so on.

>>> b=np . array ( [ ( 1 . 5 , 2 , 3 ) , ( 4 , 5 , 6 ) ] )
>>> b
array ( [ [ 1 . 5 , 2 . , 3 . ] ,
[ 4 . , 5 . , 6 . ] ] )

The type.of the array can also be explicitly specified at creation time:

>>> c=np . array ( [ [ 1 , 2 ] , [ 3 , 4 ] ] , dtype=np.complex)
>>> c
array ( [ [ 1 .+0 . j , 2 . + 0 . j ] ,
[ 3 . +0 . j , 4 . + 0 . j ] ] )

Often the elements of an array are initially unknown, but array size is known. Hence, NumPy offers several functions to create array with initial placeholder content. The function zeros ( ) create an array full of zeros, the function ones ( ) create an array full of ones, and the function empty ( ) create an array whose initial content is random. By default, the dtype of the created array is f loat6 4.

>>> np. zeros ( ( 3 , 4 ) )
array ( [ [ 0 . , 0 . , 0 . , 0 . ] ,
             [ 0 . , 0 . , 0 . , 0 . ] ,
             [ 0 . , o . , 0 . , 0 . ] ] )
>>> np . zeros [ 3 , 4] ) 
array ( [ [ 0 . , o . , o . , 0 . ] ,
           [ o . , o . , o . , 0 . ] ,
           [ o . , o . , o . , 0 . ] ] )
>>> np . ones ( ( 2 , 3 , 4 ) , dtype=np . int16 ) 
array ( [ [ [ 1 , 1 , 1 , 1 ] ,
           [ 1 , 1 , 1 ] ,
           [ 1 , 1 , 1 , 1] ] ,

           [ [ 1 , 1 , 1 , 1 ] ,
           [ 1 , 1 , 1 , 1 ] ,
           [ 1 , 1 , 1 , 1 ] ] ] , dtype=intl6 )
>>> np . empty ( ( 2 , 3 ) )
array ( [ [ 1 . 39069238e-309 , 1 . 39069238e-309 , 1 . 39069238e-309 ] ,
           [ 1 . 39069238e-309 , 1 . 39069238e-309 , 1 . 39069238e-309 ] ] )

 

To create sequences of numbers, NumPy provides a function arange ( ), analogous to Python’s built- in function range ( ), that returns array instead of list.

>>> np . arange ( 10 , 30 , 5 ) 
array ( [ 10 , 15 , 20 , 25 ] )
>>> np . arange ( 0 , 2 , 0 . 3 )
array ( [ 0 . , 0 . 3 , 0 . 6 , 0 . 9 , 1 . 2 , 1 . 5 , 1 . 8 ] )

When arange ( ) is used with floating point arguments, it is generally not possible to predict the number of elements obtained, due to the finite floating point precision. For this reason, it is usually better to use the function linspace ( ), that receives as an argument the number of elements that we want, instead of the step:

>>> np . linspace ( 0 , 2 , 5 )
array ( [ 0 . , 0 . 5 , 1 . , 1 . 5 , 2 . ] )
>>> np . linspace ( 0 , np . pi , 4 )
array ( [ 0 . , 1 . 04719755 , 2 . 0943951 , 3 . 14159265 ] )

Printing array

While printing an array, NumPy display it in a similar way to nested lists, but with the following layout:

  • the last axis is printed from left to right.
  • the second-to-last is printed from top to bottom.
  • the rest are also printed from top to bottom, with each slice separated from the next by an empty line.
>>> np . arange ( 6 )                                                     # Id array
array ( [ 0 , 1 , 2 , 3 , 4 , 5 ] )
>>>
>>> np . arange ( 12 ) . reshape ( 4 , 3 )                       # 2d array
array ( [ [ 0 , 1 , 2 ] ,
           [ 3 , 4 , 5 ] ,
           [ 6 , 7 , 8 ] ,
           [ 9 , 10 , 11 ] ] )
>>>
>>> np . arange ( 24 ) . reshape ( 2 , 3 , 4 )                    # 3d array
array ( [ [ [ 0 , 1 , 2 , 3 ] ,
           [ 4 , 5 , 6 , 7 ] , 
           [ 8 , 9 , 10 , 11 ] ]

          [ [12 , 13 , 14 , 15 ] ,
          [ 16 , 17 , 18 , 19 ] ,
          [ 20 , 21 , 22 , 23 ] ]

If an array is too large to be printed, NumPy automatically skips the central part of the array and only print the corners:

>>> np . arange ( 10000 )
array ( [ 0 , 1 , 2 , 9997 , 9998 , 9999 ] )
>>>
>>> np . arange ( 10000 ) . reshape ( 100 , 100 )
array ( [ [ 0 , 1 , 2 , . . . , 97 , 98 , 99 , ] , 
[ 100, 101, 102, . . . , 197 , 198 , 199 ] ,
[ 200 , 201 , 202 , . . . , 297 , 298 , 299 ] ,
. . . 
[ 9700 , 9701 , 9702 , . . . , 9797 , 9798 , 9799 ] ,
[ 9800 , 9801 , 9802 , . . . , 9897 , 9898 , 9899 ] ,
[ 9900 , 9901 , 9902 , . . . , 9997 , 9998 , 9999 ] ]

To disable this behaviour and force NumPy to print the entire array, the printing option set_printoptions need to be changed.

>>> np . set_printoptions ( threshold=' nan '

Python Programming – NumPy Array Read More »

Python Programming – Inheritence

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

Python Programming – Inheritence

Inheritence

A class can be based on one or more other classes, called its “base class(es)”. It then inherits the data attributes and methods of its base classes. This is called “inheritance”, and the class which inherits from the base class is called “derived class”. A class definition first evaluates the inheritance list, if present. A simple form of derived class definition looks like this:

class DerivedClassName ( BaseClassName ) :
<statement-1> 
.
.
.
<statement-N>

In place of a base class name BaseClassName, other arbitrary expressions are also allowed. This is useful, for example, when the base class is defined in another module:

class DerivedClassName ( modname . BaseClassName ) :

The following example demonstrates class inheritance.

class Parent:                              # Base class definition
parentAttr=100

def ___init___ ( self ) :
        print "Base class"

def parentMethod ( self ) :
         print ' Base class method '

def setAttr ( self , attr ) :
          Parent.parentAttr=attr

def getAttr ( self ) :
    print "Parent attribute : " , Parent . parentAttr

class Child ( Parent ) :               # Derived class definition

def ___init___ ( self ) :
      print " Derived class "

def childMethod ( self ) :
print ' Derived class method '

c=Child ( ) 
c . childMethod ( ) 
c . parentMethod ( ) 
c.setAttr ( 200 ) 
c . getAttr ( )

The output is:

Derived class 
Derived class method 
Base class method 
Parent attribute : 200

Execution of a derived class definition proceeds in the same way as for a base class. If a requested attribute is not found in the class, the search proceeds to look in the base class. This rule is applied recursively if the base class itself is derived from some other class.

The following example is a step further in understanding inheritance.

class Person :
population=0

def ___init___ ( self , Name , Age ) :
         self . name=Name 
         self . age=Age
        Person . population+=1

def Record ( self ) :
          print ( ' Name : " { 0 } " Age : { 1 }" ' . format ( self . name , self . age ) )

class Employee ( Person ) :
def ___init___ ( self , Name , Age , Salary ) :
           Person. ___init___ ( self , Name , Age )
           self . salary=Salary
           print ( ' Entered record for { 0 } ' . format ( self . name ) )

def Record ( self ) :
       Person . Record ( self )
       print ( ' Salary : " { 0 : d } " ' . format ( self . salary ) )

class Employer ( Person ) :

def ___init___ ( self , Name , Age , Percentage ) :
          Person. ___init___ ( self , Name , Age )
          self . percentage=Percentage
          print ( 'Entered record for { 0 } ' .format ( self . name ) )

def Record ( self ) :
       Person . Record ( Self )
       print ( ' Partnership percent : "{ 0 : d }" ' . format ( self . percentage ) )

employee1=Employee ( ' Ram ', 26 , 25000 ) 
employee2=Employee ( ' Ahmed ' , 20 , 50000 )
employee3=Employee ( ' John ' , 22 , 75000 ) 
employer1=Employer ( ' Michael ' , 58 , 60 ) 
employer2=Employer ( ' Kishah ' , 52 , 40)

members=[employee1 , employee2 , employee3 , employer1,employer2] 
for member in members : 
member . Record ( )

The output is:

Entered record for Ram 
Entered record for Ahmed
Entered: record for John .
Entered record for Michael 
Entered record for Kishan 
Name : " Ram " Age : " 26 "
Salary : " 25000 " 
Name : " Ahmed " Age : " 20 " 
Salary : " 50000 " 
Name : " John " Age : " 22 "
Salary : " 75000 " 
Name : "Michaei " Age : " 58 "'
Partnership percent : " 60 "
Name : " Kishan " Age : " 52 " 
Partnership percent : " 40 "

Please note that, if a base class has an ___init___ ( ) method, the derived class’s ___init___ ( ) method, if any, must explicitly call it, to ensure proper initialization of the base class part of the instance; for example : BaseClass. ___init____ ( self , [ args . . . ] ).

New-style and classic classes

Classes and instances come in two flavors: old-style (or classic) and new-style. New-style classes were introduced in Python 2.2. For compatibility reasons, classes are still old-style by default. Any class which inherits from object is a new-style class. The object class is a base for all new style classes. The following is an example showing simple definitions of old-style and new-style classes.

>>> class ClassicExample :
. . .               def ___init___ ( self ) :
. . .               pass
. . . 
>>> class NewStyleExample ( object ) :
. . .                def ___init___ ( self ) :
. . .                       pass 
. . .
>>>

Overriding Methods

Derived classes may override methods of their base classes. A method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it.

# InheritenceExample2 . py

class Parent :                                                                # Base class definition

def printlnfo ( self ) :
                  print ' Base class method '

def parentMethod ( self ) :
                   self . printlnfo ( )

class Child ( Parent ) :                                                   # Derived class definition

def printlnfo ( self ) :
       print ' Derived class method '

c=Child ( ) 
c . parentMethod ( )

The output is:

Derived class method

It can be seen that printlnfo ( ) of derived class is called instead of base class.

Super ( ) function

The is a built-in function super ( ), which can be used for accessing inherited methods that have been overridden in a class. The super ( ) only works for new-style classes; in a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable.

class Parent ( object ) :                              # Base class definition

def printlnfo ( self ) :
            print ' Base class method '
            def parentMethod ( self ) :
            self . printlnfo ( )

class Child ( Parent ) :                              # Derived class definition

def printinfo ( self ) :
              super ( Child , self ) . printlnfo ( )
#            Parent . printlnfo ( self ) 
              print ' Derived class method '

e=Child ( )
c . parentMethod ( )

The output is:

Base class method 
Derived class method

In the above example, to access the printlnfo ( ) method of Parent class, super ( ) method in the form of super (Child, self) .printlnfo () is used, where the name of base class is not mentioned. The other way would have been by using Parent .printlnfo (self).

Name mangling

In Python, there is a mechanism called “name mangling” to avoid name clashes of names in class with names defined by sub-classes. Any identifier of the form ____spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname___ spam, where classname is the current class name. Note that, the mangling rule is designed mostly to avoid accidents.

# InheritenceExample3 . py

Class Parent :                                       # Base class definition

def ___printlnfo ( self ) :
         print ' Base class method '

def parentMethod ( self ) :
             self. ___print Info ( )

class Child (Parent) :                         # Derived class definition

def printlnfo ( self ) :
          print ' Derived class method '

c=Child ( ) 
print Parent. ___diet___ . keys ( )
print Child. ___diet___ . keys ( )
c . parentMethod ( )
c ._Child___printlnfo ( )
c . _Parent___printlnfo ( )

The output is:

[ ' ____module___ ' , ___Parent___printlnfo ' , ' ____doc___ ' , ' parentMethod ' ]
[' ____module ____ ' , ' ___doc____ ' , ' ___Child____printlnfo ' ]
Base class method 
Derived class method 
Base class method

Multiple inheritence

Till now, the discussion was about inheriting from one class; this is called “single inheritance”. Python also supports “multiple inheritance”, where a class can inherit from more than one class. A simple class definition inheriting from multiple base classes looks like:

class DerivedClassName ( Base1 , Base2 , Base3 ) :
<statement-1>
.
.
.
<statement-N>

Whenever there is a call via DerivedClassName class instance, Python has to look-up the possible function in the class hierarchy for Basel, Base2 , Base3 , but it needs to do this in a consistent order. To do this, Python uses an approach called “method resolution order” (MRO) using an algorithm called “C3” to get it straight.

Consider the following multiple inheritance example.

class A ( object ) :
        def printlnfo ( self ) : 
         print ' Class A '

class B ( A ) : 
       def printlnfo ( self ) : 
       print ' Class B '
#     super ( B , self ) . printlnfo ( )
        A . printlnfo ( self )

class C ( A ) :
         def printlnfo ( self ) : 
         print ' Class C ' 
         super ( C , self ) . printlnfo ( )
class D ( B , C ) : 
       def printlnfo ( self ) : 
       print ' Class D ' 
       super ( D , self ) . printlnfo ( ) 
foo=D ( )
foo . printInfo ( )

Running the code yield the following output.

Class D
Class B
Class A

It can be observed that C class printlnfo ( ) is skipped. The reason for that is because B class printlnfo ( ) calls A class printlnfoO directly. The purpose of super ( ) is to entertain method resolution order. Now un-comment super (B, self) .printlnfoO and comment-out A. print Info (self). The code now yields a different result.

Class D 
Class B 
Class C 
Class A

Now all the printinfo ( ) methods get called. Notice that at the time of defining B. print Info ( ), one can think that super (B, self) .printlnfo ( ) is the same as calling A. print Info (self), however, this is wrong. In the above situation, super (B, self). print Info ( ) actually calls C . printInfo ( self ).

Python Programming – Inheritence Read More »

Python : Check if a List Contains all the Elements of Another List

In Python, the list datatype is that the most versatile, and it are often written as an inventory of comma-separated values (items) enclosed in square brackets.

Given two lists, the task is to check whether the second list has all the elements of first list.

Examples:

Input:

givenlist1 = ['Hello' , 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech','Geeks']
Output:
givenlist2 has all of the  givenlist1 elements

Input:

givenlist1 = ['Hello' , 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech','Geeks','pink']
Output:
givenlist2 doesn't have all of the  givenlist1 elements

Determine whether  a list is included inside another list

There are several ways to check if a list is contained in another list some of them are:

Method #1:Using any() function

The function any() returns True if any of the items in an iterable are true; otherwise, False. The any() function returns False if the iterable object is empty.

Convert list2 to Iterable and check if any element in Iterable, i.e. list2, exists in list1.

Below is the implementation:

# given two lists
givenlist1 = ['Hello', 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech', 'Geeks']
# using any()
if(any(element in givenlist1 for element in givenlist2)):
    print("givenlist2 has all of the  givenlist1 elements")
else:
    print("givenlist2 doesn't have all of the  givenlist1 elements")

Output:

givenlist2 has all of the  givenlist1 elements

Method #2:Using all() function

In a single line, the all() function is used to check all the elements of a container. Checks if all elements from one list are present in another list.

Below is the implementation:

# given two lists
givenlist1 = ['Hello', 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech', 'Geeks']
# using all()
if(all(element in givenlist1 for element in givenlist2)):
    print("givenlist2 has all of the  givenlist1 elements")
else:
    print("givenlist2 doesn't have all of the  givenlist1 elements")

Output:

givenlist2 has all of the  givenlist1 elements

Method #3:Using set.issubset()

The most commonly used and recommended method for searching for a sublist. This function is specifically designed to determine whether one list is a subset of another.

Below is the implementation:

# given two lists
givenlist1 = ['Hello', 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech', 'Geeks']
# using set.issubset() function
if(set(givenlist2).issubset(set(givenlist1))):
    print("givenlist2 has all of the  givenlist1 elements")
else:
    print("givenlist2 doesn't have all of the  givenlist1 elements")

Output:

givenlist2 has all of the  givenlist1 elements

Related Programs:

Python : Check if a List Contains all the Elements of Another List Read More »