#27 Python Programming – Mathematical Functions & List P03

Python Programming – Mathematical functions & List

Teknonauts

Mathematical functions

Python supports a wide variety of mathematical functions.

FunctionReturnsExample
abs(x)Returns the absolute value of xx = -35;x = abs(x)
print(x)
cmp(x,y)Returns -1 if x < y>
Returns 0 if x equals to y 
Returns 1 if x > y.
x = 6; y = 4
print( cmp(x,y) )
exp(x)Returns the exponential of ximport math
x = 6; print( math.exp(x) )
log(x)The natural logarithm of ximport math
x = 6; print( math.log(x) )
log10(x)The base-10 logarithm of ximport math
x = 6; print( math.log10(x) )
pow(x,y)The result of x**yimport math
x = 6; print( math.pow(x,2) )
sqrt(x)The square root of ximport math
x = 6; print( math.sqrt(x) )

List

  • Python List is a collection of data like array in Perl, shell script & ruby
  • Here data are not strictly of same type. It’s not like C – array
  • Data in side list are ordered elements (index based)
  • List are mutable  i.e., we can modify the content of the list
  • Lists have methods that allow you to manipulate the values inside them. 
  • Python list elements are separated by comma
  • List elements are enclosed by square brackets  [  ]

How to create a list?

Syntax:- 

listname= [data1, data2, data3, data4,data5….dataN ]

db=[ “oracle” , “sql”,”mysql”,”DB2”,”sqlite”]

|__ list name

[“oracle” , “sql” ,”mysql”,”DB2”,”sqlite” ]

      0            1           2           3             4     index

# List index starts at 0

To determine list type using type function

>>>  db=[ “oracle” , “sql”,”mysql”,”DB2”,”sqlite”]
>>> type(db)

Accessing list values

=> List of elements accessed using the list name

>>>print db   
#output
[ “oracle” , “sql”,”mysql”,”DB2”,”sqlite”]

Access single data from list

Syntax:-

listname [index number ]

Example:-

# print 0th index data

>>>print db[0]
#output
'oracle'
# print 1st index data
>>>print db[1]
'sql'
5-4-3-2-1Index From Right to Left
[‘Oracle’,‘sql’,‘mysql’,DB2’,‘sqlite’]
01234Index from Left to Right

Slice Operator

db=[ “oracle” , “sql”,”mysql”,”DB2”,”sqlite”]
print db[1:3]  #output [ ‘sql’,  ‘ mysql’ ]
print db[2:]    #output  [‘mysql’,’db2’,’sqllite’ ]
print db[:2]   #output   [‘oracle',’sql`]

Create employee list

>>>emp=[ ‘E123’, ‘Mr.Visa’, ‘sales’,’10.20.30.40.50’,’12995.46’ ]
>>>print emp
[ ‘E123’, ‘Mr.Visa’, ‘sales’,’10.20.30.40.50’,’12995.46’ ]
>>>print  “Hello ”,emp [1]
Hello  Mr.Visa
>>>print  emp[1] ,” working department is: ”,emp[2]
 # Mr.Visa working department is sales

Update list values

# Modify sales department in to PRODUCTION

# we can modify list values through index

Syntax :-  

listname[index]= “updated value”

>>>emp[2]=”PRODUCTION”  
>>>print   emp[1] ,”Current working department is:”,emp[2]
Mr.Visa Current working department is PRODUCTION

Find the size of list

  • Use len() function to display the total number of elements in the list.
>>>a1=[ 10,20,’data’,’/etc/passwd’,’10.20.30.40’ ]
>>>print  len(a1)  
5
  • Re-cap len() we used in string to count the number of characters
>>>print  len(“Ab”)
2

Delete List Elements

  •  To remove a list element, you can use the del() function

Syntax:- del(listname)

Example:-

>>>a1=[ 10,20,’data’,’/etc/passwd’,’10.20.30.40’ ]
>>>print  a1
[ 10,20,’data’,’/etc/passwd’,’10.20.30.40’ ]
>>>print len(a1)
 5
>>>del(a1) # delete a list name
>>>a2= [ ‘data1’,’data2’,’data3’ ]
           #    0th         1st         2nd    index
>>>print  “Total no.of elements :”, len(a2)  
Total no.of elements: 3
>>>del(a2[1])  # delete 1st index data
>>>print  “Total no.of elements :”, len(a2)
Total no.of elements: 2

Basic List operations

  • List respond to the + and * operators much like strings; + Operator is used for list concatenation and * is used for list repetition operators .
>>>L1=[‘data1’,’data2’,’data3’]
>>>L2=[10, 20, 30]
>>>L1+ L2
[ ‘data1’, ’data2’, ’data3’ ,10 ,20 ,30 ]
>>>L1*3
[‘data1’,’data2’,’data3’, ‘data1’, ’data2’,’data3’, ‘data1’, ’data2’,’data3’]

Membership operators with list

>>>L1=[‘data1’,’data2’,’data3’]
>>> ‘data1’  in  L1   # test  data1 is placed in the given list (L1) 
True
>>> ‘dataX’  in  L1  # test dataX is placed in the given list( L1) 
False
>>> ‘data1’ not in L1
False
>>> ‘dataX’ not in L1  # test dataX is not placed in the given list
True

List Based Method

Syntax:-   sorted(list)          #  displays sorted order of elements

>>>sh=[”expect”,”csh”,”tcsh”,”bash”]
>>>sorted(sh)  
bash ,csh ,expect,tcsh  

Syntax:- 

cmp(list1,list2)          #compares corresponding elements of two lists.

list1 – This is the first list to be compared.

list2 – This is the second list to be compared.

  • If elements are of the same type, perform the compare and return the result.
  • If elements are different types, check to see if they are numbers.
  • If numbers, perform numeric coercion if necessary and compare.
  • If either element is a number, then the other element is “larger” (numbers are “smallest”).
  • Otherwise, types are sorted alphabetically by name.
l1=[‘a’,’b’]
l2=[‘a’,’b’]
l3=[‘A’,’b’]
cmp(l1,l2)  ==> 0
cmp(l1,l3) ==> 1
cmp(l3,l1)   ==> -1

Syntax:- 

len(list)          #returns the number of items in list

list – list for which number of elements is to be counted.

l1=[‘data1’,’data2’,’data3’]
print  “Total no.of elements:”,len(l1)  ==> Total no.of elements: 3

Syntax:-

 max(list)          #returns the elements from the list with maximum value.

L1=[10,20,330,500,25]
print max(L1) ==> 500

Syntax:- 

min(list)          # returns the elements from the list with minimum value.

L1=[10,20,330,500,25]
print min(L1) ==> 10

List methods

  • To get list of methods type help() function with  argument as a list
>>> help(list)

The method append() appends a passed data into the existing list.

Syntax:-

list.append (data)

>>>sh=[‘/bin/sh’, ‘/bin/bash’,’/usr/bin/tcsh’]
>>>sh.append(‘/usr/bin/perl’)  # adding “/usr/bin/perl”  to  existing list

This method does not return any value but updates existing list.

>>> sh=[‘/bin/sh’, ‘/bin/bash’,’/usr/bin/tcsh’]

>>> sh.append(‘/usr/bin/perl’)  # adding “/usr/bin/perl”  to  existing list
>>> sh
[ ‘/bin/sh’, ‘/bin/bash’,’/usr/bin/tcsh’,’/usr/bin/perl’ ]
  • The method count() returns count of how many times data occurs in list.

Syntax:-

List.count(‘data’)

>>>L1=[‘unix’,’linux’,’unix’,’aix’,’linux’,’winx’]
>>>print L1.count(‘linux’)  
2
>>>print L1.count(‘winx’)
1
  • The method extend() appends the contents of seq to list

Syntax :-

List.extend(seq)  where  Seq is collection of elements 

L1=[‘unix’,’linux’,’aix’]
L2=[‘data1’,’data2’]
L1.extend(L2)
print “Extended List :”, L1
Extended List :[ ‘unix’,’linux’,’aix’,’data1’,’data2’]
L3=[‘unix’,’linux’,’aix’]
print “Extend list:”, L3.extend(“ABC”)
Extend list: [‘unix’,’linux’,’aix’,’A’,’B’,’C’]
  • The method index() returns the lowest index in list where data appears

Syntax:-

List.index(data)
  • This method returns index of the found object otherwise raises an exception indicating that value does not found.
>>>L1=[‘unix’,’linux’,’aix’]
>>>print L1.index(‘linux’)
1
  • The method insert() inserts object data into list at offset index.

Syntax:-

List.insert(index,data)

index – This is the Index where the object obj need to be inserted.

data – This is the data to be inserted into the given list

  • This method does not return any value but it inserts the given element at the given index.
L1=[‘unix’,’linux’,’aix’]
L1.insert(2,”SOLARIS”)
>>> L1
[‘unix’,’linux’,’SOLARIS’,’aix’]
  • The method pop() removes and returns last data  from the list.

Syntax:-

List.pop()
List.pop(data)
=>   This method returns the removed object from the list.
L1=[‘unix’,’linux’,’aix’,’solaris’,’winx’]
>>> L1.pop()
‘winx’
>>> L1.pop(2)
‘aix’
  • This method remove() does not return any value but removes the given object from the list.

Syntax:-

List.remove(data)
L1=[‘unix’,’linux’,’aix’,’solaris’,’winx’]
L1.remove(‘linux’) # remove linux element from L1 list
  • The method reverse() does not return any value but reverse the given object in the list.

Syntax:- List.reverse()


>>> L1=[‘unix’,’linux’,’aix’,’solaris’,’winx’]
>>> L1.reverse()
>>> L1
[‘winx’,’solaris’,’aix’,’linux’,’unix’]
  • The method sort() sorts objects of the list

Syntax:-

List.sort()

  • This method does not return any value but it changes the original list
  • Compare sorted() function returns the list of data in sorted order but keeps the original values unchanged
>>>L1.sort()
>>>L1
[‘aix’,’linux’,’solaris’,’unix’,’winx’]

Tuple

  • Python tuple  is a collection of data like array in Perl, shell script, ruby
  • Here data are not strictly of same type. It’s not like C – array
  • Data in side list are ordered elements (index based) like list
  • Unlike List, Tuple is a sequence of immutable elementsmeans that tuple elements cannot be updated or modified.
  • Like List, tuple have methods that allow you only to perform manipulation on the values inside them. 
  • Python tuple elements are separated by comma
  • Tuple elements are enclosed by parentheses

How to create a tuple?

Syntax:-

tuplename= ( data1, data2, data3, data4,data5….dataN  )
db=(  “oracle” , “sql”,”mysql”,”DB2”,”sqlite” )
|__ tuple name
>>> type(db)

Print elements of tuple

>>> print db
(“oracle” , “sql”, “mysql”, “DB2”,”sqlite”)

Accessing Single data from the Tuple

Syntax:-

Tuplename[index]

>> db=(“oracle” , “sql”, “mysql”, “DB2”,”sqlite”)
#print  1st index data from tuple
print db[1]  => like list 'sql'
print db[2:]  => from 2nd index to list of all  (‘mysql’,’DB2’,’sqlite’)

Basic Tuple operation

Syntax:-

tuplename.count (Value) 

# return integer total number of occurrence of a given value.
db=(‘oracle’,’sql’,’oralce’,’mysql’)
db.count(‘oracle’)  ==>  2

Syntax:-

len(tuplename)

db=(“oracle” , “sql”, “mysql”, “DB2”,”sqlite”)
print “Total no.of DB’s :”,len(db)  
# Total no.of DB’s : 5
  • Removing individual tuple elements is not possible.
  • append () or insert() is not used in tuple.
  • We can’t modify single data from tuple
  • Like List, Tuple supports min() , max() cmp() functions.
  • tuple(seq) –  Converts a list into tuple.
  • list(seq) –Converts a tuple into list 

Advantages of Tuple over List

  1. Since, tuples are quite similar to lists; both of them are used in similar situations as well.
  2. However, there are certain advantages of implementing a tuple over a list.
  3. Below listed are some of the main advantages
    1. Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight performance boost.
    2. Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not possible.
    3. If you have data that doesn’t change, implementing it as tuple will guarantee that it remains write-protected.

Reference

https://www.python.org/

Continue exploring at Teknonauts.com

Leave a Reply

Your email address will not be published. Required fields are marked *