Python

Python Numpy : Select rows / columns by index from a 2D Numpy Array | Multi Dimension

Working with Numpy Arrays: Indexing

You have to be familiar with indexing if you want to work with Numpy arrays and matrices. You will use them when you would like to work with a subset of the array.

About 2d numpy array:

These dimentionals arrays are also known as matrices which can be shown as collection of rows and columns. In this article, we are going to show  2D array in Numpy in Python. NumPy is a very important library in python. We used NumPy for adding support for large multidimensional arrays & matrices .

Importing numpy module in your project:

import numpy as np

Indexing a Two-dimensional Array

import numpy as np
array1 = np.arange(12).reshape(4,3)
print(array1)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]

Here we use two indices,one we use for rows and one for column.Both the column and the row indices start from 0.

So in above all example we are going to use same matrices.

Select a single element from 2D Numpy Array by index

We can use [][] tese brackets to select an element from Numpy Array .

array1[row_index][column_index]

So if i want to access the element ‘10,’ we use the index ‘3’ for the row and index ‘1’ for the column.

import numpy as np
array1 = np.arange(12).reshape(4,3)
array1= array1[3][1]
print(array1)

Output:

RESTART: C:/Users/HP/Desktop/article2.py

10

Select Rows by Index from a 2D Numpy Array

We can use [] this bracket to select a single or multiple row. For single row use-

array1[row_index]

Let’s take an example,

import numpy as np
array1 = np.arange(12).reshape(4,3)
row = array1[1]
print(row)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[3 4 5]

For multiple rows use,

array1[start_index: end_index , :]

Let’s take an example,

import numpy as np
array1 = np.arange(12).reshape(4,3)
rows = array1[1:3, :]
print(rows)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[[3 4 5]
[6 7 8]]

Select Columns by Index from a 2D Numpy Array

Syntax for single column use,

array1[ : , column_index]

Lets take an example,

import numpy as np
array1 = np.arange(12).reshape(4,3)
column = array1[:, 1]
print(column)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[ 1 4 7 10]

Syntax to select multiple columns,

ndArray[ : , start_index: end_index]

Lets take an example,

import numpy as np
array1 = np.arange(12).reshape(4,3)
columns = array1[: , 1:3]
print(columns)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[[ 1 2]
[ 4 5]
[ 7 8]
[10 11]]

Select a Sub Matrix or 2d Numpy Array from another 2D Numpy Array

For sub 2d Numpy Array we pass the row & column index range in [] .

Syntax for this is,

ndArray[start_row_index : end_row_index , start_column_index : end_column_index]

lets take an example,

import numpy as np
array1 = np.arange(12).reshape(4,3)
sub2DArr = array1[1:3, 1:3]
print(sub2DArr)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[[4 5]
[7 8]]

Selected Row or Column or Sub Array is View only

This is for view only i.e. if there is  any modification in returned sub array will be reflected in original Numpy Array .

We are going to take same array which we have created in start of this article.

import numpy as np
array1 = np.arange(12).reshape(4,3)
row = array1[1]
print(row)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[3 4 5]

Now for any modification in the same row,

import numpy as np
array1 = np.arange(12).reshape(4,3)
row = array1[1]
row[:] = 20
print(row)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[20 20 20]

Modification in sub array will be shown in main Numpy Array too. Updated \ 2D Numpy Array array1 are,

[[ 0     1      2]
[20    20     20]
[ 6     7      8]
[ 9    10   11]]

Get a copy of 2D Sub Array from 2D Numpy Array using ndarray.copy()

Create a 2D Numpy array1 with3 rows & columns | Matrix

import numpy as np
array1 = np.array(([12, 22, 13], [21, 25, 30], [33, 17, 19]))
print(array1)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[[12 22 13]
[21 25 30]
[33 17 19]]

Select a copy of row at index 1 from 2D array and set all the elements in selected sub array to 20.

array1 = np.array(([12, 22, 13], [21, 25, 30], [33, 17, 19]))
row=array1[1].copy()
row[:] = 20
print(row)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[20 20 20]

Conclusion:

So in this article we have seen how to work with NumPy arrays.Hope you have understood everything.

Python Numpy : Select rows / columns by index from a 2D Numpy Array | Multi Dimension Read More »

Python Programming – Data Structures

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

Python Programming – Data Structures

A data structure is a group of data elements grouped together under one name. Python’s data structures are very intuitive from a syntax point of view, and they offer a large choice of operations. This chapter tries to put together the most common and useful information about various data structures. Some of the Python’s data structures that are discussed in this book are list, tuple, set, and dictionary.

Types of Data Structures in Python
Python has implicit support for Data Structures which enable you to store and access data. These structures are called List, Dictionary, Tuple and Set.

Python allows its users to create their own Data Structures enabling them to have full control over their functionality. The most prominent Data Structures are Stack, Queue, Tree, Linked List and so on which are also available to you in other programming languages. So now that you know what are the types available to you, why don’t we move ahead to the Data Structures and implement them using Python.

TreeStructure-Data-Structures-in-Python

Built-in Data Structures
As the name suggests, these Data Structures are built-in with Python which makes programming easier and helps programmers use them to obtain solutions faster. Let’s discuss each of them in detail.

Python Programming – Data Structures Read More »

Python Programming – Tuple

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

Python Programming – Tuple

Tuple

There is also another sequence type- tuple. Tuples is a sequence just like list. The differences are that tuple cannot be changed i.e. tuple is immutable, while list is mutable, and tuple use parentheses, while list use square brackets. Tuple items need not to be of same data type. Also, as mentioned previously, Python allow adding a trailing comma after last item of tuple.

>>> a= ( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a
( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a= ( ' spam ' , ' eggs ' , 100 , 1234 , )
>>> a
( ' spam ' , ' eggs ' , 100 , 1234 )

The above expressions are examples of a “tuple packing” operation i.e. the values ‘ spam ‘, ‘ eggs ‘, 10 0, and 123 4 are packed together in a tuple. The reverse operation is also possible, for example:

>>> a1 , a2 , a3 , a4=a 
>>> a1
' spam '
>>> a2 ' eggs '
>>> a3 100
>>> a4 1234

This is called “sequence unpacking”, and works for any sequence on the right-hand side. Sequence unpacking requires the group of variables on the left to have the same number of elements as the length of the sequence. Note that multiple assignments are really just a combination of tuple packing and sequence unpacking.

>>> a , b=10 , 20 
>>> a 
10
>>> b 
20

Tuple creation

Tuple can be created in many ways.

Using parenthesis

Creating a tuple is as simple as grouping various comma-separated-values, and optionally these comma-separated values between parentheses.

>>> a= ( ' spam ' eggs ' 100 , 1234 )
>>> a
( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a= ( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a
( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a= ' spam ' , ' eggs ' , 100 , 1234 
>>> a
( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a= ' spam ' , ' eggs ' , 100 , 1234 ,
>>> a
( ' spam ' , ' eggs ' , 100 , 1234 )

A tuple with one item is created by a comma after the item (it is not necessary to enclose a single item in parentheses).

>>> a= ( 10 )
>>> a 
10
>>> type ( a )
<type ' int ' >
>>> b= ( 10 ,)
>>> b
( 10 , )
>>> type ( b )
<type ' tuple ' >
>>> c=10,
>>> c
( 10 , )
>>> type ( c )
<type ' tuple ' >

It is also possible to create an empty tuple by assigning parenthesis to a variable.

>>> a= ( ) 
>>> a
( )

Using other tuples

A tuple can also be created by copying a tuple or slicing a tuple.

>>> a= ( ' spam ' , ' eggs ' , 100 , 1234 )
>>> b=a [ : ]
>>> b
( ' spam ' , ' eggs ' , 100 , 1234 )
>>> c=a [ 1 : 3 ]
>>> c
( ' eggs ' , 100 )

Using built-in function

Tuple can also be created using the built-in function tuple ( ). The tuple ( [iterable] ) function return a tuple whose items are the same and in the same order as items of the iterable. The iterable may be a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. If no argument is given, an empty tuple is returned.

>>> tuple ( [ ' apple ' , ' pineapple ' , ' banana ' ] )
( ' apple ' , ' pineapple ' , ' banana ' )
>>> tuple ( ' apple ' )
( ' a ' , ' p ' , ’ p ' , ’ 1 ’ , ’ e ’ )
>>> tuple ( [ ' apple ' ] ) 
( ' apple ' , )

Accessing tuple elements

The tuple index starts with 0, and to access values in a tuple, use the square brackets with the index or indices to obtain a slice of the tuple.

>>> a= ( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a[ 0 ]
' spam '
>>> a [ 1 : 3 ]
( ' eggs ' , 100 )

Update tuple

Tuple is immutable, so changing element value or adding new elements is not possible. But one can take portions of existing tuples to create a new tuples.

>>> tuple1= ( 1 , 2 , 3 )
>>> tuple2=( ' a ' , ' b ' , ' c ' )
>>> tuple3=tuple1+tuple2 
>>> tuple3
( 1 , 2 , 3 , ' a ' , ' b ' , ' c ' )
>>> tuple3=tuple1 [ 0 : 2 ]+tuple2 [ 1 : 3 ] 
>>> tuple3
( 1 , 2 , ' b ' , ' c ' )

It is also possible to create tuple which contain mutable objects, such as lists.

>>> a= [ 1 , 2 , 3 ] , [ 4 , 5 , 6 , 7 ]
>>> a
( [ 1 , 2 , 3 ] , [ 4 , 5 , 6 , 7 ] )
>>> a [ 0 ] [ 1 ]=200
>>> a 
( [ 1 , 200 , 3 ] , [ 4 , 5 , 6 , 7 ] )

Deleting tuple

Removing individual tuple elements is not possible. To explicitly remove an entire tuple, just use the del statement.

>>> a= ( ' spam ' ' eggs ' , 100 , 1234 )
>>> del a

Swapping tuples

There might be a scenario in which multiple tuples needs to be swapped among themselves. This is can done easily using multiple assignments expression.

>>> a= ( 10 , 20 , 30 )
>>> b= ( 40 , 50 , 60 )
>> c= ( 70 , 80 , 90 )
>>> a , b , c=c , a , b 
>>> a
( 70 , 80 , 90 )
>>> b
( 10 , 20 , 30 )
>>> c
( 40 , 50 , 60 )

Python Programming – Tuple Read More »

Python : 6 Different ways to create Dictionaries

How we can create dictionaries by multiple ways in python ?

Dictionary in python is one of the important datatype which is used to store data values in key : value pair.

Syntax of dictionary :

dictionary_name = {key1: value1, key2: value2}

where,

  • key1, key2… represents keys in a dictionary. These keys can be of any data type like string, integer, tuple, etc. But keys needs to be unique.
  • value1, value2… represents values in dictionary. These values can be numbers, strings, list or list within a list etc.
  • key and value is separated by : symbol.
  • key-value pair symbol is separated by , symbol.

Approach-1: Creating Empty Dictionary :

By 2 ways we can create empty dictionary.

Method-1 : By using { } empty brackets :

Let’s see the implementation of it with a program.

#Program :

# Empty dictionary created using empty brackets
covid_case_dict = {}
print(covid_case_dict)
Output :
{ }

Method-2: By using using dict() :

Let’s see the implementation of it with a program.

#Program :

# Empty dictionary created using dict()
covid_case_dict = dict()
print(covid_case_dict)
Output :
{ }

Approach-2: Creating Dictionaries with literals :

By passing key : value pairs literals we can create dictionary.

Let’s see the implementation of it with a program.

#Program :

# dictionary created using key-value literals
covid_case_dict = {"January":100000, "February":200000, "March":300000}
print(covid_case_dict)
Output :
{"January":100000, "February":200000, "March":300000}

Approach-3: Creating Dictionaries by passing parameters in dict constructor :

By creating dictionary constructor and passing  key-value pairs within it also we can create a dictionary.

Let’s see the implementation of it with a program.

#Program :

#dictionary created using dictionary constructor
covid_case_dict = dict(January=100000, February=200000, March=300000)
print(covid_case_dict)
Output :
{"January":100000, "February":200000, "March":300000}

Approach-4: Creating Dictionaries by a list of tuples :

We can create a dictionary by passing  list of tuple within dict constructor.

Let’s see the implementation of it with a program.

#Program :

# list of tuples
list_of_Tuples = [("January",100000), ("February",200000), ("March",300000)]
#dictionary created by passing tuple in dict constructor
covid_case_dict = dict(list_of_Tuples)
print(covid_case_dict)
Output :
{"January":100000, "February":200000, "March":300000}

Approach-5: Creating a Dictionary by a list of keys and initializing all with the same value :

We can create a dictionaries by assigning same vales to all the keys.

Suppose we a dictionary of keys. Let’s see how we can initialize all keys with same value.

#Program :

# list of keys 
covid_case_list = ["Januray", "February", "March"]
# create and Initialize a dictionary 
#use list elements as keys and with same value 100000
covid_case_dict = dict.fromkeys(covid_case_list,100000 )
print(covid_case_dict)
Output :
{"January":100000, "February":100000, "March":100000}

Approach-6: Creating a Dictionary by two lists :

If we have two lists, then also we can create a dictionary. For that we can use the elements of the first list as keys and we can use the elements of the second list as values.

In python there is a zip( ) function which we will be used and it will iterate over two lists parallelly.

Let’s see the implementation of it with a program.

#Program :

# First list, its elements will be used as keys 
covid_case_list1 = ["Januray", "February", "March"]

# Second list, its elements will be used as values
covid_case_list2 = [100000, 200000, 300000]
#two lists are merged using zip() to create dictionary
covid_case_dict = dict( zip(covid_case_list1,covid_case_list2))
print(covid_case_dict)
Output : 
{"January":100000, "February":100000, "March":100000}

Python : 6 Different ways to create Dictionaries Read More »

Remove a key from Dictionary in Python | del vs dict.pop() vs comprehension

How to remove a key from dictionary using del vs dict.pop() vs comprehension in python ?

As we know, Dictionary plays an important role in python data structure.

  • The elements are written with in { }curly brackets, having keys and values.
  • Each key-value pair mapped with the key to its related value.
  • In Dictionaries duplicates are not allowed.
Syntax : mydict = {key1: value1, key2: value2}

In this article, we will discuss about different ways to remove a key from dictionary in python.

Let us assume we have a dictionary with correspondent keys and values:

#dictionary with keys with their correspondent values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}

Now we will see different method to delete an key from dictionary :

Method -1 : Using dict.pop( ) method :

This pop() method is used to delete a key and its value in its place. The advantage over using del is that it provides a mechanism to print the desired value if you try to remove a non-existent spelling. Secondly it also returns the value of the key that is removed as well as performs a simple delete operation.

#Program :

#dictionary test_dict
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
#this key will be deleted
key_to_be_deleted = 'Sagar'
# As 'Sagar' key is present in dictionary, so pop() will delete
# its entry and return its value
result = test_dict.pop(key_to_be_deleted, None)
print("Deleted item's value = ", result)
print("Updated Dictionary :", test_dict)
Output
Deleted item's value = 36
Updated Dictionary : {'Ram': 32, 'Dhruv': 45}

In case the key does not exist :

We use try/except method to avoid error. We know key ‘Soni’ is not in dictionary. So, an error will generate. To avoid error try/except method will be used.

#Program :

#dictionary test_dict
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}

#Deleting key which does not exist i.e Soni
key_to_be_deleted = 'Soni'
try:
    test_dict.pop(key_to_be_deleted)
except KeyError:
    print('That Key is not in the dictionary')
Output :
That is not present in the dictionary

Method-2 : Using items() & for loop :

By using item() method and for loop we will iterate over the dictionary. When the key that will be deleted will be matched then delete that key.

Let’s see a program how it’s implemented.

#Program :

# Dictionary with keys and values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# key that to be deleted
key_to_be_deleted = 'Dhruv'
new_dict = {}
#using for loop 
#Iterate one by one key#If found that key then delete
for key, value in test_dict.items():
 if key is not key_to_be_deleted:
  new_dict[key] = value
test_dict = new_dict
print(test_dict)
Output
{'Ram': 32, 'Dhruv': 45}

Here for deletion we used for loop and We created a new temporary dictionary and then duplicated it for all key-value pairs in the original dictionary. During iteration, we copy the key and value pair into a new temporary dictionary only if the key is not equal to the key to be deleted. Once the duplication finished, we copied the contents of the new temporary dictionary into the original dictionary.

Method-3: Using items() & Dictionary Comprehension :

Utilizing the logic of the above example we use items() & dictionary comprehension.

#Program :

# Dictionary with keys and values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# key that to be deleted
key_to_be_deleted = 'Ram'
test_dict = {key: value for key, value\
                  in test_dict.items()\
                  if key is not key_to_be_deleted}
print(test_dict)
Output:
{'Ram': 32, 'Dhruv': 45}

Method-4: Using del keyword :

We can use the del statement to delete a key-value pair from the dictionary regarding on the key.

Syntax : del dict[key]

Let’s use it-

#Program :

# Dictionary of keys &values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# Deleting an item from dictionary using del
del test_dict['Dhruv']
print(test_dict)
Output:
{'Sagar': 36, 'Ram':32}

In case the key does not exist :
Suppose we want to delete key 'Soni', which does not exist then we can use try-except to avoid any exception.

Let’s see the implementation of it.

#Program :

# Dictionary of keys &values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# If key exist in dictionary then delete it using del.
key_to_be_deleted = 'Soni'
try:
 del test_dict[key_to_be_deleted]
except KeyError:
 print('That key is not present in the dictionary')
Output:
That key is not present in the dictionary

Remove a key from Dictionary in Python | del vs dict.pop() vs comprehension Read More »

Python Programming – Some List Operations

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

Python Programming – Some List Operations

Some list operations

Some of the list operations supported by Python are given below.

Concatenation

List concatenation can be carried out using the + operator.

>>> [ 1 , 2 , 3 ] +[ ' hi ' , ' hello ' ]
[ 1 , 2 , 3 , ' hi ' , ' hello ' ] ;

Repetition

The * operator can be used to carry out repetition operations.

>>> [ ' Hey ' ] *3 
[ ' Hey ' , ' Hey ' , ' Hey ' ]

Membership operation

The list also supports membership operation i.e. checking the existence of an element in a list.

>>> 4 in [ 6 , 8 , 1 , 3 , 5 , 0 ]
False 
>>> 1 in [ 6 , 8 , 1 , 3 , 5 , 0 ]
True

Slicing operation

As list is a sequence, so indexing and slicing work the same way for list as they do for strings. All slice operations return a new list containing the requested elements:

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ 2 ] 
100
>>> a [ -2 ]
100
>>> a [ 1 : 3 ] 
[ ' eggs ' , 100 ]
>>> a [ : ]
[ ' spam ' , ' eggs ' , 100 , 1234 ]

List slicing can be in form of steps, the operation s [ i: j: k ] slices the list s from i to j with step k.

>>> squares=[ x**2 for x in range ( 10 ) ] 
>>> squares
[ 0 , 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 , 81 , 100 , 121 , 144 , 169 , 196 ]
>>> squares [ 2 : 12 : 3 ]
[ 4 , 25 , 64 , 121 ]

Slice indices have useful defaults, an omitted first index defaults to zero, an omitted second index defaults to the size of the list being sliced.

>>> squares= [ x**2 for x in range ( 10 ) ]
>>> squares 
[0 , 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 , 81 , 100 , 121 , 144 , 169 , 196 ]
>>> squares [ 5 : ]
[ 25 , 36 , 49 , 64 , 81 , 100 , 121 , 144 , 169 , 196 ]
>>> squares [ : 5 ]
[ 0 , 1 , 4 , 9 , 16 ]

Python Programming – Some List Operations Read More »

Python Programming – Modules and Packages

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

Python Programming – Modules and Packages

As the program gets longer, it is a good option to split it into several files for easier maintenance. There might also be a situation when the programmer wants to use a handy function that is used in several programs without copying its definition into each program. To support such scenarios, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter.

Module

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Definitions from a module can be imported into other modules. For instance, consider a script file called “fibo.py” in the current directory with the following code.

# Fibonacci numbers module

def fib ( n ) :                                        # write Fibonacci series up to n
         a , b=0 , 1 
         while b<n :
            print b , 
            a, b=b , a+b

def fib2 ( n ) :                                    # return Fibonacci series up to n
          result= [ ] 
          a , b = 0 , 1 
          while b<n:
               result . append ( b ) 
          a , b=b , a+b 
   return result

Now on the Python interpreter, import this module with the following command:

>>> import fibo

Within a module, the module’s name (as a string) is available as the value of the global variable
___name___:

>>> fibo.___name___ 
' fibo '

Use the module’s name to access its functions:

>>> fibo . fib ( 1000 )
1 1 2 3 5 8  13  21  34  55  89  144  233  377  610  987 
>>> fibo . fib2 ( 1000 )
[ 1 ,  1 ,  2 ,  3 ,  5 ,  8 ,  13 ,  21 ,  34 ,  55 ,  89 ,  144 ,  233 ,  377 ,  610 ,  987 ]

If it is intended to use a function often, assign it to a local name:

>>> Fibonacci=fibo . fib 
>>> Fibonacci ( 500 )
1  1  2  3  5  8  13  21  34  55  89  144  233  377

Python Programming – Modules and Packages Read More »

Python Programming – Modules

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

Python Programming – Modules

Modules

A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement; they also run if the file is executed as a script.

Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables.

Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module. The imported module names are placed in the importing module’s global symbol table.

There is a variant of the import statement that imports specific names from a module directly into the importing module’s symbol table. For example, specific attributes of fibo module are imported in the local namespace as:

>>> from fibo import fib, fib2 
>>> fib ( 500 )
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This does not introduce the module name from which the imports are taken in the local symbol table (so in the example, fibo is not defined).

There is even a variant to import all names that a module defines:

>>> from fibo import *
>>> fib ( 500 )
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This imports all names except those beginning with an underscore ( _ ).

Note that in general, the practice of importing * from a module or package is discouraged, since it often causes poorly readable code. However, it is touse it to save typing in an interactive sessions. For efficiency reasons, each module is only imported once per interpreter session. If changes are made in many modules, it is a wise approach to restart the interpreter or if it is just one module that needs to be tested interactively, use reload (), e.g. reload (modulename).

Executing modules as scripts

When a Python module is run at command prompt

$ python fibo . py <arguments>

the code in the module will be executed, just as if it imported, but with the ___name___ set to ___main___ . That means, by adding the following code at the end of the module:

if __name___ == " ___main___ " :
import sys
fib ( int ( sys . argv [ 1 ] ) )

the file is made usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file:

$ python fibo . py 50 
1 1 2 3 5 8 13 21 34

The Module Search Path

When a module named f ibo is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named fibo.py in a list of directories given by the variable sys. path. The variable sys. the path is initialized from some of these locations:

  • The current directory.
  • PYTHONPATH environment variable (a list of directory names, with the same syntax as the shell variable PATH).

After initialization, Python programs can modify sys .path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory.

Math module

Python has math module and it is always available. The functions provided in this module cannot be used with complex numbers; use the functions of the same name from the cmath module for support of complex numbers. The distinction between functions which support complex numbers and those which does not is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Except when explicitly noted otherwise, all functions return float values.

Python Programming – Modules Read More »

Python Programming – Random module

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

Python Programming – Random module

Random module

This module implements pseudo-random number generators for various distributions. Almost all module functions depend on the basic function random ( ), which generates a random float uniformly in the semi-open range [0 . 0 , 1 . 0 ). Python uses the “Mersenne Twister” as the core generator. However, Mersenne Twister being completely deterministic, it is not suitable for all purposes and is completely unsuitable for cryptographic purposes.

Functions for integers

random.randrange ( stop )

Return a randomly selected integer element from range ( 0 , stop ) .

>>> random . randrange ( 88 )
17
>>> random . randrange ( -88 )

Traceback ( most recent call last ) :
File "<pyshell#l>" , line 1 , in <module> 
random . randrange ( -88 )
File " C : \ Python27 \ lib \ random . py " , line 191 , in randrange 
raise ValueError , " empty range for randrange ( ) "
ValueError: empty range for randrange ( )

random . randrange ( start , stop [ , step ] )
Return a randomly selected integer element from range ( start , stop , step ) .

>>> random . randrange ( 3 , 100 , 5 )
83

random . randint ( a , b )
Return a random integer N such that a<=N<=b.

>>> random . randint ( 5 , 86 )
70

Functions for sequences

random . choice ( seq )
Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.

>>> random . choice ( ' abcdefghij ' )
' e ' 
>>> random . choice ( [ ' aa ' , ' bb ' , ' cc ' , 11 , 22 ] )
' cc '

random . shuffle ( x [ , random ] )
Shuffle the sequence x in place. The optional argument random is a O-argument function returning a random float in [ 0 . 0 , 1 . 0 ); by default, this is the function random ( ).

>>> items= [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
>>> random . shuffle ( items )
>>> items
[ 4 , 7 , 2 , 6 , 3 , 5 , 1 ]

random . sample ( population , k )
Return a k length list of unique elements chosen from the population sequence; used for random sampling without replacement. Return a new list containing elements from the population, while leaving the original population unchanged. If the population contain repeating elements, then each occurrence is a possible selection in the sample.

>>> random . sample ( [ 1 , 2 , 3 , 4 , 5 ] , 3 )
[ 4 , 5 , 1 ]

To choose a sample from a range of integers, use an xrange ( ) object as an argument. This is especially fast and space efficient for sampling from a large population.

>>> random . sample ( xrange ( 10000000 ) , 5 )
[ 2445367 , 2052603 , 975267 , 3021085 , 6098369 ]

Functions for floating point values

random . random ( )
Return the next random floating point number in the range [ 0 . 0 , 1 . 0 ).

>>> random . random ( )
0.6229016948897019

random . uniform ( a , b )
Return a random floating point number N, such that a<=N<=b for a<=b and b<=N<=a for b<a.

>>> random . uniform ( 0 . 5 , 0 . 6 )
0.5795193565565696

random . triangular ( low , high , mode )
Return a random floating point number N such that low<=N<=high and with the specified mode between those bounds. The low and high bounds default to 0 and 1, respectively. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution.

>>> random . triangular ( 2 . 8 , 10 . 9 , 7 . 5 )
6.676127015045406

random . betavariate ( alpha , beta )
Beta distribution; conditions of the parameters are alpha>0 and beta>0. Returned values range between 0 and 1.

>>> random . betavariate ( 2 . 5 , 1 . 0 )
0.543590525336106

random . expovariate ( lambd )
Exponential distribution; lambd is 1.0 divided by the desired mean. It should be nonzero. Returned values range from 0 to positive infinity; if lambd is positive, and from negative infinity to 0, if lambd is negative.

>>> random . expovariate ( 0 . 5 )
1.5287594548764503

random . gammavariate ( alpha , beta )
Gamma distribution (not the gamma function). Conditions of the parameters are alpha>0 and beta>0.

>>> random . gammavariate ( 1 . 3 , 0 . 5 )
0.5893587279305473

random . gauss ( mu , sigma )
Gaussian distribution; mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate () function defined below.

>>> random . gauss ( 0 . 5 , 1 . 9 )
-1.8886943114939512

random . lognormvariate ( mu , sigma )
Log normal distribution; if natural logarithm of this distribution is taken, a normal distribution with mean mu, and standard deviation sigma is received, mu can have any value, and sigma must be greater than zero.

>>> random . lognormvariate ( 0 . 5 , 1 . 9 )
4.621063728160664

random . normalvariate ( mu , sigma )
Normal distribution; mu is the mean, and sigma is the standard deviation.

>>> random . normalvariate ( 0 . 5 , 1 . 9 )
1.6246107732503214

random . vonmisesvariate ( mu , kappa )
mu is the mean angle, expressed in radians between 0 and 271, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2K .

>>> random . vonmisesvariate ( 0 . 5 , 1 . 9 )
-0.4664831190641767

random . paretovariate ( alpha )
Pareto distribution; alpha is the shape parameter.

>>> random . paretovariate ( 0 . 5 )
60.471412103322585

random . weibullvariate ( alpha , beta )
Weibull distribution; alpha is the scale parameter and beta is the shape parameter.

>>> random . weibullvariate ( 0 . 5 , 1 . 9 )
0.9229896561284915

Alternative generators

Apart from Mersenne Twister, there are more core random number generator, such as generator based on “Wichmann-Hill” algorithm.

>>> rnd=random . WichmannHill ( )
>>> rnd . random ( )
0.4065226158909223
>>>
>>> rnd=random . SystemRandom ( )
>>> rnd . random ( )
0.46579102190832355

Python Programming – Random module Read More »

7 Ways to add all elements of list to set in python

How to add all elements of list to set in python ?

As we know a set in python is a built-in  data type which stores multiple unordered items in a single variable.

Example of a set

my_set = {10,20,30,40}

Where,

  • A set contains unique values.
  • All items placed inside { }.

Similarly, a list in python is a built-in  data type which is used to store items of different types.

Example of list

my_list = {30,40,50,60,70}

where,

  • A list contains different types of values integer, float, string etc.
  • All items placed inside [ ].

When we will add all the items of the list to set it will look like this

{10,20,30,40,50,60,70}

Here, all the items are unique after adding as because list contains unique elements.

Method-1 : Add all elements of a list to set using update( ) function

Set class provides an update( ) method with the help of which all elements of list can be added to set.

Syntax : set.update(sequences)
#Program :
    
#Represents a set
my_set = {10, 20, 30, 40}
#Represents a list
my_list = [30, 40, 50, 60, 70, 80]
# adding all elements in list to the set
my_set.update(my_list)
print('After adding list to set : ')
print(my_set)
Output :
After adding list to set : 
{10,20,30,40,50,60,70,80}

In the above program we just passed the list inside the update( ) method, the elements which are not present in set those got added and the elements which are present in set those got skipped as set contains only unique elements.

Method-2 : Add all elements of a list to set using add( ) function

Set class provides an add( ) method with the help of which all elements of list can be added to set.

Syntax : set.add(element)

But the thing is that, add( ) only accept single element inside that. So, if we will pass list in that it will give TypeError: unhashable type: ‘list’ as output.

So to avoid this error we can use for loop and pass one by one element of the list inside add( ) method.

#Program :

#Represents a set 
my_set = {10, 20, 30, 40} 
#Represents a list 
my_list = [30, 40, 50, 60, 70, 80] 
# adding all elements in list to the set 
# By iterating over all elements of list using for loop
for item in my_list:
    # adding each element to the set
    my_set.add(item)
print('After adding list to set : ') 
print(my_set)
Output : 
After adding list to set : 
{10,20,30,40,50,60,70,80}

Method-3 : Add a list to set using add() & union()

We can add content of two sets by using union( ) method.

Syntax : s.union(t)
#Program : 

#Represents a set 
my_set = {10, 20, 30, 40} 
#Represents a list 
my_list = [30, 40, 50, 60, 70, 80] 
#convert list to set
#then add contents two sets 
my_set = my_set.union(set(my_list)) 
print('After adding list to set : ') 
print(my_set)
Output : 
After adding list to set : 
{10,20,30,40,50,60,70,80}

Method-4 : Add all elements in a list to set using | operator

By creating union of 2 sets by using | operator , then we can add elements of two sets. So we have to convert our list to set by using | operator.

#Program :

#Represents a set 
my_set = {10, 20, 30, 40} 
#Represents a list 
my_list = [30, 40, 50, 60, 70, 80] 
# adding all elements in list to the set 
# by converting list to set 
# then get union of both the sets using | operator
my_set  |= set(my_list )

print('After adding list to set : ') 
print(my_set)
Output : 
After adding list to set : 
{10,20,30,40,50,60,70,80}

Method-5 : Add a list to set using |= and unpacking list to set

We will add the elements of list to set just like previous solution means we will convert list to set then we will add the elements by finding union of two sets.

But we will convert list to set by string literal and unpacking our lists elements inside it.

#Program : 

#Represents a set 
my_set = {10, 20, 30, 40} 
#Represents a list 
my_list = [30, 40, 50, 60, 70, 80] 
# adding all elements in list to the set 
# by converting list to set 
# then get union of both the sets using | operator 
# Unpacking elements and OR that with original set
my_set |= set(*my_list ) 
print('After adding list to set : ') 
print(my_set)
Output : 
After adding list to set : 
{10,20,30,40,50,60,70,80}

Add all elements from multiple lists to the set :

Suppose we have 2 different list then add the elements of both the list to set.

#Program : 

#Represents a set 
my_set = {10, 20, 30, 40} 

#Represents a list 
my_list1 = [30, 40, 50, 60, 70] 
my_list2= [80,90] 
# adding all elements in list to the set 
my_set.update(my_list1,my_list2) 
print('After adding list to set : ') 
print(my_set)
Output : 
After adding list to set : 
{10,20,30,40,50,60,70,80,90}

7 Ways to add all elements of list to set in python Read More »