UNIT-2 Arrays in Python
UNIT-2 Arrays in Python
UNIT-2 Arrays in Python
UNIT-II :: ARRAYS,STRINGS,CHARACTERS
Arrays in Python
Arrays
Types of Arrays
Creating Arrays
Operations on Arrays
Attributes of an Array
reshape(),flatten() methods
Matrices in NumPy
Operations on Strings
Sorting Strings
Searching Strings
Arrays
An array is defined as a collection of items that are stored
at contiguous memory locations.
It is a container which can hold a fixed number of items,
and these items should be of the same type.
Arrays
Array can be handled in Python by a module named
array
array(data_type, value_list)
is used to create an array with data type and
value list specified in its arguments.
importing array module and creating array can be done
in following ways
or
2. from array import *
array_identifier = array (datatype, value_list)
ARRAY METHODS
Python has a set of built-in methods that you can use on
lists/arrays.
append(element)
insert(index , element)
extend(list)
index(element)—first occurence
remove(element)—first occurence
pop()
reverse()
count(element)
Basic Operations
Traverse
Insert
Search
Delete
Update
NUMPY IN PYTHON
NumPy is the fundamental package for scientific
computing in Python.
Example : a=np.array([(1,2,3),(4,5,6)])
a1D = np.array([1, 2, 3, 4])
Syntax:
arange([start,] stop[, step,][, dtype])
start : [optional] start of interval range. By default start
=0
np.arange(2, 3, 0.1)
output:
array([ 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9])
Ar=np.arange(20)
Ar.shape
Ar1=np.arange(20).reshape(4,5)
Ar1.shape
Ar2=np.arange(27).reshape(3,3,3)
Ar2.shape
Ex: np.zeros(5)
np.zeros((5,), dtype=int)
np.zeros((2,1))
PARAMETERS OF ZEROS FUNCTION
shape int or tuple of ints --Shape of the new array, e.g., (2,
3) or 2.
dtype--data-type, optional The desired data-type for the
array, e.g., numpy.int8. Default is numpy.float64.
order{‘C’, ‘F’}, optional, default: ‘C’Whether to store
multi-dimensional data in row-major (C-style) or
column-major (Fortran-style) order in memory.
like array_likeReference object to allow the creation of
arrays which are not NumPy arrays.
ones---Return a new array of given shape and type, filled with
ones.
np.ones(5)
np.ones((5,), dtype=int)
np.ones((2,1))
full---Return a new array of given shape and type, filled with
fill_value
shape
dtype
itemsize
nbytes
T
ATTRIBUTES OF AN ARRAY
a.shape=(3,2)
ATTRIBUTES OF AN ARRAY
x = np.array([1, 2, 3, 4, 5])
print('The data type of array x is', x.dtype)
import numpy as np
x = np.array([1,2,3,4,5], dtype = np.int8)
print x.itemsize
Addition
np.add(x,y)
Subtraction
np.subtract(x,y)
Multiply
np.multiply(x,y)
np.dot(x,y)
STRINGS IN PYTHON
A String is a sequence of characters. It is a derived data type.
Strings are immutable.
When we use triple quotes, strings can span several lines without
using the escape character.
Creating strings is as simple as assigning a value to a variable.
For example −
var1 = 'Hello World!'
var2 = "Python Programming"
STRINGS IN PYTHON
Multiline Strings
We can assign a multiline string to a variable by using three
quotes:
Example :
a = "Hello, World!"
print(a[1]) /// prints character-’e’ of index:1
Check String
To check if a certain phrase or character is present in a string,
we can use the keyword in.
Ex: txt = "The best things in life are free!"
print("free" in txt) //returns true
STRINGS IN PYTHON
Check if NOT
To check if a certain phrase or character is NOT present in a
string, we can use the keyword not in.
Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
Ex: b = "Hello, World!"
print(b[-5:-2])
output : orl
STRINGS IN PYTHON
Modify Strings
The upper() method returns the string in upper case
a = "Hello, World!"
print(a.upper())
Remove Whitespace
Whitespace is the space before and/or after the actual text
STRINGS IN PYTHON
The strip() method removes any whitespace from the beginning
or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Replace String
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
STRINGS IN PYTHON
Split String
The split() method returns a list where the text between the
specified separator becomes the list items.
Ex:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Concatenation
To concatenate, or combine, two strings you can use the +
operator.
STRINGS IN PYTHON
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c=a+b
print(c)
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
o/p: I want 3 pieces of item 567 for 49.95 dollars
STRINGS IN PYTHON
Use index numbers {0} to be sure the arguments are placed in
the correct placeholders
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item
{1}."
print(myorder.format(quantity, itemno, price))
find() -----Searches the string for a specified value and returns the
position of where it was found.
Sort Ascending
a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a)
print(x)
Sort Descending
a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a, reverse=True)
print(x)
SEARCHING STRING
The find() method finds the first occurrence of the
specified value.
The find() method returns -1 if the value is not found.
Syntax:
string.find(value, start, end)
value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the
end of the string
SEARCHING STRING
Ex :
txt = "Hello, welcome to my world."
x = txt.find("e")
x = txt.find("e", 5, 10)
print(txt.find("q"))
print(txt.index("q"))