Venkateshwarlu.webs.com
Arrays
An array is an object that stores a group of elements of same data type. Arrays can store only one type of data. It means, we can store only integer type elements or only float type elements into an array. But we cannot store one integer, one float and one character type element into the same array.
Arrays can increase or decrease their size dynamically. It means, we need not declare the size of the array. When the elements are added, it will increase its size and when the elements are removed, it will automatically decrease its size in memory.
Advantages:
• Arrays are similar to lists. The main difference is that arrays can store only one type of elements; whereas, lists can store different types of elements. When dealing with a huge number of elements, arrays use less memory than lists and they offer faster execution than lists.
• The size of the array is not fixed in python. Hence, we need not specify how many elements we are going to store into an array in the beginning.
• Arrays can grow or shrink in memory dynamically (during runtime).
• Arrays are useful to handle a collection of elements like a group of numbers or characters.
• Methods that are useful to process the elements of any array are available in “array ” module.
Creating an array:
In general arrays are created using array( ) method.
array( ) : We can create an array from a regular Python using the array function. The type of the
resulting array is deduced from the type of the elements in the sequences.
Syntax: arrayname = array(type code, [elements])
The type code represents type array. The type code character should be written in single quotes.
After that the elements should be written in inside the square braces [ ].
a = arr.array ('d', [1.1, 3.5, 4.5])
Here, we created an array of float type. The letter 'd' is a type code.
|Type code |C Type |Python Type |Minimum size in bytes |
|'b' |signed char |int |1 |
|'B' |unsigned char |int |1 |
|'u' |Py_UNICODE |Unicode character |2 |
|'h' |signed short |int |2 |
|'H' |unsigned short |int |2 |
|'i' |signed int |int |2 |
|'I' |unsigned int |int |2 |
|'l' |signed long |int |4 |
|'L' |unsigned long |int |4 |
|'f' |float |float |4 |
|'d' |double |float |8 |
| | | | |
Importing the Array Module:
There are two ways to import the array module into our program. The first way is to import the entire array module using import statement as,
import array
when we import the array module, we are able to get the “array” class of that module that helps us to create an array.
a = array.array(‘i’, [4,8,-7,1,2,5,9] )
Here the first “array‟ represents the module name and the next “array‟ represents the class name for which the object is created. This means, we are creating an array as an object of array class.
The next way of importing the array module is to write:
from array import *
Here , the “*” symbol that represents “all”. The meaning of this statement is, import all (classes, objects, variables, etc) from the array module into our program. That means significantly importing the “array” class of “array” module. So, there is no need to mention the module name before our array name while creating it. We can create array as:
a = array(‘i’, [4,8,-7,1,2,5,9] )
Example: from array import *
arr = array(„i‟, [4,8,-7,1,2,5,9]) for i in arr:
print i,
Output: 4 8 -7 1 2 5 9
Indexing and slicing of arrays:
An index represents the position number of an element in an array. For example, when we creating following integer type array:
a = array(‘i’, [10,20,30,40,50] )
Python interpreter allocates 5 blocks of memory, each of 2 bytes size and stores the elements 10, 20, 30, 40 and 50 in these blocks.
[pic]
Slicing : The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. It is used to get a part of or all the elements of array.
Ex: from array import *
a=array('i', [10,20,30,40,50,60,70])
print ("length is", len(a))
print (" 1st position Element ", a[1] )
print ("Elements from 2 to 4", a[2:5] )
print ("Elements from 2 to end", a[2:] )
print ("Elements from start to 4", a[:5] )
print ( " Elements from start to end", a[:] )
a[3]=45; a[4]=55
print ("Elements from start to end after modifications ",a[:] )
Array Methods (Processing of Array):
|Method |Description |
|a.append(x) |Adds an element x at the end of the existing array a. |
|a.count(x) |Returns the number of occurrences of x in the array a. |
|a.extend(x) |Appends x at the end of the array a. “x” can be another array or iterable object. |
|a.fromfile(f,n) |Reads n items from from the file object f and appends at the end of the array a. |
|a.fromlist(l) |Appends items from the l to the end of the array. l can be any list or iterable object. |
|a.fromstring(s) |Appends items from string s to end of the array a. |
|a.index(x) |Returns the position number of the first occurrence of x in the array. |
|a.pop(x) |Removes the item x from the array a and returns it. |
|a.pop( ) |Removes last item from the array a |
|a.remove(x) |Removes the first occurrence of x in the array. Raises “ValueError” if not found. |
|a.reverse( ) |Reverses the order of elements in the array a. |
|a.tofile( f ) |Writes all elements to the file f. |
|a.tolist( ) |Converts array “a” into a list. |
|a.tostring( ) |Converts the array into a string. |
Types of Arrays:
Python supports two types of arrays
Single Dimensional Arrays:
Multi-Dimensional arrays:
Working with Numpy Arrays :
The numpy in python allows user to create an array by using the following functions.
array( ) , linspace ( ) , logspace ( ) , zeros( ) , ones( ) , arrange ( )
array( ) : Arrays can be created using array( ) function. We can specify the datatype of array elements while creating an array.
Syntax: arr_name= array([values],int)
Ex: a= array([1,2,3,4,5], int) -- creates an integer array.
numpy allows creation of array without specifying data type. Then it coverts any element data type.
Ex: a= array([1,2.5,3,4,5]) -- creates an float array. [1.0 2.5 3 4 5]
linspace ( ): This method creates an array with evenly spaced samples, calculated over the interval [start, stop].
Syntax: linspace (start, stop, num)
Start argument indicates the starting element, Stop argument indicates the ending element and num indicates the number of parts into which the array must be divided.
Ex: from numpy import *
arr = linspace(2,16,5)
print arr # arr = [2. 5.5 9. 12.5 16. ]
logspace ( ): This method creates an array with evenly numbers spaced on a log scale samples, calculated over the interval [start, stop].
Syntax: logspace (start, stop, num)
Start argument indicates the 10 to the power of starting element, Stop argument indicates the 10 to the power of ending element and num indicates the number of parts into which the array must be divided.
Ex: from numpy import *
arr = linspace(2,5,3)
print arr # arr = [100 3162 100000 ]
zeros( ) :The function zeros creates an array with full of zeros. The general syntax is as follows,
zeros(n, datatype) By default, the data type of the created array is float.
Ex: zeros(5, int) # [ 0 0 0 0 0]
ones( ) : The function ones creates an array with full of ones. The general syntax is as follows,
ones(n, datatype) By default, the data type of the created array is float.
Ex: ones(5, int) # [ 1 1 1 1 1]
empty ( ) :The function empty creates an array whose initial content is random and depends on the state of the memory.
By default, the data type of the created array is float.
arrange ( ) : It is similar to arrange( ) function. It extracts specific range of values from the array. The general syntax is:
arrange ( start, stop , stepsize)
Ex: arrange(2,10,3)
The array created with elements range from 2 to 10. And the step increment is +3. The elements of array are [ 2, 5, 8]
Python Arithmetic Operators :
|Operator |Description |
|+ Addition |Adds a value to all the elements of array. |
|-Subtraction |Subtracts a value to all the elements of array. |
|*Multiplication |Multiplies a value to all the elements of array. |
|/Division |Divides all the elements of array by a value. |
|% Modulus |Divides all the elements of array by a value and returns remainder |
a=array([10,20,30,40,50])
print(“adding by 2:” , a+2)
print(“subtracting by 5:” , a-5)
print(“Multiplying by 2:” , a*2)
print(“Dividing by 2:” , a/2)
print(“Modulus by 3:” , a%2)
Mathematical Operations:
Python allows various mathematical operations to be performed on array elements. The numpy module provides the following methods for performing mathematical operations.
Comparison Operators to compare Arrays :
Python allows us to compare the elements of two arrays using comparison operators.
|Operator |Description |Example |
|== |If all values of two arrays are equal, then the condition becomes true. |(a == b) |
|!= |If all values of two arrays are not equal, then condition becomes true. |(a != b) |
|> |If all the values of left array are greater than all the value of right array, then condition becomes |(a > b) |
| |true. | |
|< |If all the values of left array are less than all the value of right array, then condition becomes true. |(a < b) |
|>= |If all the values of left array are greater than or equals to all the value of right array, then condition|(a >= b) |
| |becomes true. | |
|1,a1,a= . The compariision is done by python interpreter based on English dictionary. The result of these operators either True or False.
Syntax : string1 operator string2
import numpy
import string
str1 = “python”
str2 = “physics”
print(“ srt1== str2 ” , str1==str2)
print(“ srt1!= str2 ” , str1!=str2)
print(“ srt1< str2 ” , str1= str2 ” , str1>=str2)
Removing Space :
Python considers the space as a one character within the string. If unnecessary spaces are exist in the string, then it generates incorrect results while performing string operations. The unnecessary spaces can be removed by using following metods.
1. rstrip( ) 2. lstrip( ) 3. strip ( )
1. rstrip( ): This method removes right side spaces of the string.
string_name.rstrip( );
2. lstrip( ): This method removes left side spaces of the string
string_name.lstrip( );
3. strip( ): This method removes right side spaces of the string
string_name.strip( );
Ex: str =“ welcome ”
print(str.rstrip( )) # displays “ welcome”
print(str.lstrip( )) # displays “welcome ”
print(str.strip( )) # displays “welcome”
Built-in String methods for Strings:
Find Sub String: The find ( ) method searches the string for a specified character and returns the position of where it was found. It returns -1 if not found.
Syntax : stringname.find(‘character’,start,end)
Ex: str =“welcome”
print (str.find(‘c’,0,6)) # DISPLAYS 3
We can also use find without passing start and end arguments. Then total string will be searched.
Ex: print (str.find(‘c’)) # DISPLAYS 3
Counting Substrings: The count( ) method returns the number of times a specified substring occurs in a string
Syntax : stringname.count(‘substring’,start,end)
Ex: str =“welcome”
print (str.count(‘e’,0,6)) # DISPLAYS 2
Replacing String : The replace( ) method replaces every occurrence of a substring with a specified new string.
Syntax : stringname.replace(‘substring’, ‘new string’)
Ex: str =“welcome to python”
print (str.replace(‘to’, ‘TO’)) # DISPLAYS welcome TO python
Splitting and Joining of String:
split( ) : This method used to split the string at every occurrence of the specified separator or delimiter and stored into list. Here the default delimiter is ‘space’. The various delimiters are allowd in python are ‘ ,’ ‘-’ ‘:’
Syntax : stringname.split(delimiter)
Ex: str =“welcome to python”
print(str.split( )) # displays [‘welcome’, ‘to’ , ‘python’]
join( ) : A set of strings are joined into single string in python by using join ( ) method.
Syntax: separator. join( str)
Ex: str = (“JAVA” , “ PYTHON” , “ C++”)
print(“:”.join(str)) # displays JAVA: PYTHON:C++
|replace( ) |Returns a string where a specified value is replaced with a specified value |
|split( ) |Splits the string at the specified separator, and returns a list |
|join( ) |Joins the elements of the string using separator. |
|find( ) |Searches the string for a specified value and returns the position of where it was found |
|index( ) |Searches the string for a specified value and returns the position of where it was found |
|count( ) |Returns the number of times a specified value occurs in a string |
|startswith( ) |Returns true if the string starts with the specified value |
|endswith( ) |Returns true if the string ends with the specified value |
|center( ) |Returns a cantered string |
Change Case Methods in String
|upper( ) |Converts a string into upper case |
| |Stringname . upper( ) |
| |Ex: str= “welcome” print(str.upper( )) |
|lower( ) |Converts a string into lower case |
| |Stringname . lower( ) |
| |Ex: str= “PYTHON” print(str.lower( )) |
|casefold( ) |Converts a string into lower case |
| |Stringname . casefold( ) |
| |Ex: str= “PYTHON” print(str.casefold( )) |
|title( ) |Converts the first character of each word of the string to upper case |
| |Stringname . title( ) |
| |Ex: str= “welcome to python” print(str.title( )) |
|capitalize( ) |Converts the first character of string to upper case |
| |Stringname . capitalize( ) |
| |Ex: str= “welcome to python” print(str.capitalize ( )) |
|swapcase( ) |Swaps cases, lower case becomes upper case and vice versa |
| |Stringname . swapcase( ) |
| |Ex: str= “WelCome To Python” print(str.swapcase ( )) |
String Testing Methods:
|isalnum( ) |Returns True if all characters in the string are alphanumeric (0-9,a-z,A-Z) |
|isalpha( ) |Returns True if all characters in the string are in the alphabet (a-z,A-Z) |
|isdigit( ) |Returns True if all characters in the string are digits (0-9) |
|isnumeric( ) |Returns True if all characters in the string are numeric (0-9) |
|isprintable( ) |Returns True if all characters in the string are printable |
|isspace( ) |Returns True if all characters in the string are whitespaces |
|isupper( ) |Returns True if all characters in the string are upper case (A-Z) |
|islower( ) |Returns True if all characters in the string are lower case (a-z) |
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
Related searches
- getroman com reviews
- acurafinancialservices.com account management
- acurafinancialservices.com account ma
- getroman.com tv
- http cashier.95516.com bing
- http cashier.95516.com bingprivacy notice.pdf
- connected mcgraw hill com lausd
- education.com games play
- rushmorelm.com one time payment
- autotrader.com used cars
- stock charts webs best
- webs free website builder