Friday, 31 March 2017

collection datatype: Tuple

tuple:

  • It can be created by using parenthesis i.e  ( ) or by using tuple function.
  • tuple is a immutable object But the elements of the tuple can be mutable or immutable.
  • tuple supports +ve and -ve indexes.

  • Insertion order is preserved.
  • Duplicate elements are allowed.
  • Heterogeneous elements are allowed.
Example1:

                  x=tuple()
                  print(x)
                  print(type(x))
                  print(len(x))

Output:
                    ( )
             <class 'tuple'>
                     0


Example2:
                    y=(10,40,20,30,10,20,1.1,True,3+4j)
                    print(y)
                    print(type(y))
                    print(len(y))

Output:
                   (10, 40, 20, 30, 10, 20, 1.1, True, (3+4j))
                   <class 'tuple'>
                     9
Example3:
                   z=11,22,33
                   print(z)
                   print(type(z))
                   print(len(z))
Output:
                 (11, 22, 33)
                <class 'tuple'>
                  3
Example4:
                a=(10,20,30,40,50)
                print(a)
                print(a[2])
                print(a[-2])
                print(a[2:5])
                print(a[5:2])
Output:
             (10, 20, 30, 40, 50)
             30
             40
            (30, 40, 50)
            ( )
Example5:
             b=tuple('python')
             print(b)
Output:
              ('p', 'y', 't', 'h', 'o', 'n')

Example6:
                p=(100,200,300)
                print(p)
                c,d,e=p
                print(c)
                print(d)
                print(e)
                print(200 in p)
                print(400  in p)
                print(200 not in p)
                print(400 not in p)
Output:
               (100, 200, 300)
               100
               200
               300
               True
               False
               False
               True

Example7: for loop
                 x=(10,20,30,40,50)
                 sum1=0
                 for i in x:
                sum1=sum1+i
                 print(sum1)
Output:
                150

Example8: while loop
                  y=(10,20,30,40,50)
                  sum2=0
                  i=0
                  while i<len(y):
                     sum2=sum2+y[i]
                     i=i+1
                  print(sum2)
Output:
                150

Example9:
                 x=((11,22,33),(44,55,66),(77,88,99))
                 for i in x:
                 print(type(i))
                 for j in i:
                print(j)
Output:
                 <class 'tuple'>
                    11
                    22
                    33
               <class 'tuple'>
                    44
                    55
                    66
             <class 'tuple'>
                   77
                   88
                   99

Example10:
                    x=((10,20,30),[40,50,60],(70,80,90))
                    print(x)
                    for p in x:
                     print(p,type(p))
                     for q in p:
                    print(q)
                    x[1][2]=555
                    print(x)
Output:
                  ((10, 20, 30), [40, 50, 60], (70, 80, 90))
                  (10, 20, 30) <class 'tuple'>
                  10
                  20
                  30
                  [40, 50, 60] <class 'list'>
                   40
                   50
                   60
                 (70, 80, 90) <class 'tuple'>
                  70
                  80
                  90
                ((10, 20, 30), [40, 50, 555], (70, 80, 90))

Methods in tuple

Example:
          x=(10,20,30,40,10,20,10)
          print(x.count(10))
          print(x.index(10))
          print(x.index(10,3))
Output:
          3
          0
          4

Note:
  • Comprehension is not supported in immutable objects.
  • If we try to apply the tuple comprehension we will not get the tuple object. But we will get the generator object.

Example:
               x=(p for p in range(10))
               print(x)
Output:
              <generator object <genexpr> at 0x0000000003523EB8>

Differences between list and tuple:

 list:     


These are mutable objects .                  

Applying the iterations on  the list objects takes longer time. 

list cannot be used as a key  for the dictionary even though list contains immutable elements.

list objects are not write  protected.

If the frequent operations are insertion,updation and deletion recommended to go for list   

tuple:

These are immutable objects.

Applying the iterations on the tuple objects takes less time. 

tuple can be used as a key for the dictionary if the tuple contains mutable elements. 

tuple objects are write protected. 

If the frequent operations are retrieval of the elements then it then is recommended to use tuple.                                                              
         

Thursday, 30 March 2017

collection data type: list part-2

Using for loops with lists:

Example:

                     list = [1,4,9,16,25]
                     sum = 0
                     for num in list:
                                sum += num
                     print (sum)  
Output:

                      55

Using if loop with lists:

Example:


                   colors = ['red', 'blue', 'green']
                   if 'blue' in colors:
                               print ('blue color is available')
Output:

                    blue color is available

Using while loops with lists:

Example:


                            i = 0
                           a = [1,2,3,4,5,6,7,8,9]
                           while i < len(a):
                                      print (a[i]) 
                                      i = i + 3


Output:


                            1
                            4
                            7

list comprehension:

  • Generating the elements into the list object by writing some logic in the list is known as a list-comprehension.
  • in order to implement the list comprehension we need list object and for loop is mandatory.
  • list comprehension with respect only mutable objects.
  • comprehension is increase the performance of the application.
Example1:


                    x=[p for p in range(5)]
                    print(x)

Output:

                 [0, 1, 2, 3, 4]


Example2:

                  x=[p*p for p in range(5)]
                  print(x)

Output:

                  [0, 1, 4, 9, 16]

Example3:

                 x=[p**p for p in range(5)]
                 print(x)

Output:

                  [1, 1, 4, 27, 256]

Example4: print the even numbers only with-out comprehension.

                     y=[ ]
                     for p in range(10):
                                     if p%2==0:
                                           y.append(p)
                     print(y)

Output:

                     [0, 2, 4, 6, 8]

Example5: print the even numbers only with comprehension.

                     x=[p for p in range(10) if p%2==0]
                     print(x)

Output:

                    [0, 2, 4, 6, 8]

Example:
                 message="Hai Siva Krishna! How Are You"
                 words=message.split(" ")
                 requirement=[ [w.upper(),w.lower(),len(w)] for w in words]
                 for i in requirement:
                           print(i)
Output:

                    ['HAI', 'hai', 3]
                    ['SIVA', 'siva', 4]
                    ['KRISHNA!', 'krishna!', 8]
                    ['HOW', 'how', 3]
                    ['ARE', 'are', 3]
                    ['YOU', 'you', 3]

Example: matrix addition

                    x=[[1,1,1],[2,2,2],[3,3,3]]
                    y=[[1,1,1],[2,2,2],[3,3,3]]
                    result=[[0,0,0],[0,0,0],[0,0,0]]

                    for i in range(len(x)):
                                for j in range(len(x[0])):
                                              result[i][j]=x[i][j]+y[i][j]

                    for r in result:
                                print(r)

Output:
                       [2, 2, 2]
                       [4, 4, 4]
                       [6, 6, 6]

Example: matrix multiplication

                     x=[[1,1,1],[2,2,2],[3,3,3]]
                     y=[[1,1,1],[2,2,2],[3,3,3]]
                     result=[[0,0,0],[0,0,0],[0,0,0]]

                     for i in range(len(x)):
                               for j in range(len(y[0])):
                                          for k in range(len(y)):
                                                      result[i][j]+=x[i][k]*y[k][j]

                    for r in result:
                                 print(r)
Output:

                    [6, 6, 6]
                    [12, 12, 12]
                    [18, 18, 18]

Wednesday, 22 March 2017

Collection Data-Types in python : list

Collection Data-Types in python:

Collection: 

collections are nothing but objects, which represents group of objects.

Group of elements into a single object, every element as a object.

Collections represents group of elements into a single entity. 

Python supports the following types of Collections,they are 
  • list
  • tuple
  • set
  • dict

Every Collection type provides some methods to perform the 

operations on the elements of Collection Objects.


list:-

  • list object can be created by using [ ] or by calling list function.
                         list1=[ ]  or  list1= list( )
  • list object is a mutable object.
  • The elements of the list can be mutable or immutable.
                  list=[ [10,20,30,40], 'siva', 3+4j, True, 3.2 ]
  • Every element in the list is represented with unique index.
  • list is supporting both +ve and -ve indexing.
  • Insertion order is preserved.
                             input: x=[10,20,30,40]

                                       print(x)
                             
                             output: [10,20,30,40]
  • Duplicate elements are allowed.
                        list1=[10,20,10,30,20,40,10]
  • Heterogeneous elements are allowed.
                        list1=[ 2, 2.3, True, 3+4j, 'siva' ]
  • list size is not fixed(it is a dynamic)
  • in a list object every element as a object
note:
list is a sequence data type, because in list insertion order preserved, means  x=[10,20,30,40]
                              print(x)
                             
                             output: [10,20,30,40]
input and output follow the same order.

Example 1:

a=[ ]
print(a)
print(type(a))
print(len(a))

Output:
[ ]
<class 'list'>
0

Example 2:

b=list()
print(b)
print(type(b))
print(len(b))

Output:

[ ]
<class 'list'>
0

Example 3:

c=[ 11,22,33,44 ]
print(c)
print(type(c))
print(len(c))

Output:

[11, 22, 33, 44]
< class 'list' >
4

Example 4:

d=[ 100, 12.34, True, 'sivakrishna', 2+3j ]
print(d)
print(type(d))
print(len(d))

Output:

[ 100, 12.34, True, 'sivakrishna',  (2+3j) ]
< class 'list' >
5

Example 5:

e=[100,200,100,300,200,100]
print(e)
print(type(e))
print(len(e))

Output:

[100, 200, 100, 300, 200, 100]
<class 'list'>
6

Example 6: retrieving the elements from list by using indexes

f=[100,200,100,300,200,100]
print(e)
print(e[3])
print(e[-2])

Output:

[100, 200, 100, 300, 200, 100]
300
200

Example 7: list slices
g=[100,200,100,300,200,100]
print(g)
print(e[2:5])
print(e[2:])
print(e[-3:-1])

Output:
[100, 200, 100, 300, 200, 100]
[100, 300, 200]
[100, 300, 200, 100]
[300, 200]

Example 8: modify/change the content in the list
h=[10,2,7,4]
print(h)
print(id(h))
h[2]="siva"
print(h)
print(id(h))

Output:
[10, 2, 7, 4]
55109640
[10, 2, 'siva', 4]
55109640

Example 9: retrieving the list element
l=[ 11, 12.23, True, 'siva', 4+6j ]
print(l)
print(type(l))
a,b,c,d,e=l
print(a,type(a))
print(b,type(b))
print(c,type(c))
print(d,type(d))
print(e,type(e))

Output:
[11, 12.23, True, 'siva', (4+6j)]
< class 'list' >
11 < class 'int' >
12.23 < class 'float' >
True < class 'bool' >
siva < class 'str' >
(4+6j) < class 'complex' >

Note: 
Python support nested list (list inside another list) mechanism.

Example:
x=[[10,20,30],[40,50,60],[70,80,90]]
print(x)
print(type(x))
print(x[0])
print(type(x[0]))
print(x[0][0])
print(type(x[0][0]))

Output:
[ [10, 20, 30], [40, 50, 60], [70, 80, 90] ]
< class 'list' >

[10, 20, 30]
< class 'list' >

10
< class 'int' >

List Methods:

Perform the some operations on list elements, python provides some predefined methods, they are

  • list.append(elem) ---> adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.
                       Example: 
                                x=[10,40,20,50]
                                print(x)
                                print(id(x))
                                x.append(30)
                                print(x)
                                print(id(x))

                      Output:
                               [10, 40, 20, 50]
                               55788040

                               [10, 40, 20, 50, 30]
                               55788040

  • list.insert(index, elem) --->  inserts the element at the given index, shifting elements to the right.
                                Example:
                                        y=[10,40,20,50]
                                        print(y)
                                        print(id(y))
                                        y.insert(2,60)
                                        print(y)
                                        print(id(y))

                              Output:
                                        [10, 40, 20, 50]
                                        19265480
                                        [10, 40, 60, 20, 50]
                                        19265480
  • list.extend(list2) ---> adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().
                              Example:
                                        a=[1,2,3,4]
                                        print(a)
                                        print(id(a))
                                        b=[5,6,7,8]
                                        print(b)
                                        print(id(b))
                                        a.extend(b)
                                        print(a)
                                        print(id(a))

                              Output:
                                        [1, 2, 3, 4]
                                        55183752
                                        [5, 6, 7, 8]
                                        55104200
                                        [1, 2, 3, 4, 5, 6, 7, 8]
                                        55183752
  • list.index(elem) --->  searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use "in" to check without a ValueError).
                                 Example:
                                            x=[10,40,20,50]
                                            print(x)
                                            print(x.index(20))

                                Output:
                                           [10, 40, 20, 50]
                                           2
  • list.remove(elem) ---> searches for the first instance of the given element and removes it (throws ValueError if not present).
                       Example
                                 c=[1,2,3,4]
                                 print(c)
                                 print(id(c))
                                 c.remove(2)
                                 print(c)
                                 print(id(c))

                       Output:
                                  [1, 2, 3, 4]
                                  55101320
                                  [1, 3, 4]
                                  55101320
  • list.sort() ---> sorts the list in place (does not return it). (The sorted() function shown below is preferred.)
                           Example:
                                        e=[10,4,2,9,6,1]
                                        print(e)
                                        print(id(e))
                                        e.sort()
                                        print(e)
                                        print(id(e))

                        Output:
                                      [10, 4, 2, 9, 6, 1]
                                      55105032
                                      [1, 2, 4, 6, 9, 10]
                                     55105032
  • list.reverse() ---> reverses the list in place (does not return it)
                            Example
                                    f=[5,2,8,1,6]
                                    print(f)
                                    print(id(f))
                                    f.reverse()
                                    print(f)
                                    print(id(f))

                           Output:
                                     [5, 2, 8, 1, 6]
                                     55173000
                                     [6, 1, 8, 2, 5]
                                     55173000
  • list.pop(index) ---> removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).
                           Example:
                                       g=[1,2,3,4,5]
                                       print(g)
                                       print(id(g))
                                       g.pop()
                                       print(g)
                                       print(id(g))
                                       g.pop(2)
                                       print(g)
                                       print(id(g))
                           Output:
                                     [1, 2, 3, 4, 5]
                                     55183752
                                     [1, 2, 3, 4]
                                     55183752
                                     [1, 2, 4]
                                     55183752



Tuesday, 21 March 2017

Python: range function

range( ) in Python:

  • it is a predefined function in python
  • range( ) function generating the group of values.
  • range value stores the group of values.
  • range value starting from zero( 0 ) by default.
type 1: 
pass one parameter or value,that value is ending value and that value is exclusive.
syntax: 
                 range(stop)
example:
range(3)

output:
range(0, 3)

Retrieve the one by one values from range by using for loop.

Example:
x=range(3)
for p in x:
    print(p)

Output:
0
1
2

Example:
x=range(3)
print(id(x))
print(type(x))
for p in x:
    print(p)
    print(type(p))
    print(id(p))

Output:
55317392
<class 'range'>
0
<class 'int'>
1926046384
1
<class 'int'>
1926046416
2
<class 'int'>
1926046448

type 2:
pass two parameters or values, first parameter or value take starting value,it is inclusive.
second parameter or value take stop value,it is exclusive.

syntax:
               range(start,stop)

here by default increment by 1

Example:
y=range(1,5)
for p in y:
    print(p)

Output:
1
2
3
4

type 3:
pass 3 parameters or values,first parameter/value takes start value,it is inclusive.
second parameter/value takes stop value,it is exclusive.
third value take step,increment/decrement value.

syntax:
                        range(start,stop, [step] )

Example:
z=range(0,10,2)
for p in z:
    print(p)

Output:
0
2
4
6
8

Example:
a=range(5,0,-1)
for p in a:
    print(p)

Output:
5
4
3
2
1

Example:
a=range(0,5,-1)
for p in a:
    print(p)

Output:
no output 

How to use range function in for loop:

Example:
for p in range(5):
    print(p)
Output:
0
1
2
3
4
Example:
for p in range(0,5):
    print(p)

Output:
0
1
2
3
4

Example:
for p in range(0,5,2):
    print(p)

Output:
0
2
4

Example:
for p in range(5,0,-2):
    print(p)

Output:
5
3
1





Python: Looping Statemnts

Looping Statements in Python:

Looping statements are used to execute the set of statements Repeatedly.

Python supports 2 types of Loops, they are
  • while loop
  • for loop
While Loop:
While loops executes the set of statements are repeatedly until condition will become False.

                                          (or)

While loops executes the repeatedly until while condition is False.

syntax 1:
                           while  condition :  statement
syntax 2:
                           while condition:
                                           statement 1
                                           statement 2
                                           --------------
                                          --------------
                                         statement n
Example 1:
i=1
sum=0
while i<=100:
    sum=sum+i
    i=i+1
print(sum)

Output:
5050

Example 2:
a=0
while a<5:
    print(a)
    a+=1

Output:
0
1
2
3
4
While loop with else:
syntax:
                         while  condition:
                                            statement 1
                                            statement 2
                                            ---------------
                                            ---------------
                                            statement n
                        else:
                              statement 1
                              statement 2
                              ---------------
                              ---------------
                              statement n

Infinite while loop:
  • Executing no.of times keep on upto sufficient memory.
  • in order to work with the infinite loops,we are using break statement
syntax:
                             while  True:
                                          -------------
                                          -------------
                                          -------------
                                          -------------

Example 1:
i=1
while True:
    print("hai siva")
    if i==5:
            i=i+1
Output:
hai siva
hai siva
hai siva
hai siva
hai siva
hai siva
hai siva
hai siva
hai siva
hai siva
hai siva
hai siva
............
...........
............
............
Traceback (most recent call last):
  File "E:/python_practice/examples/infinite while.py", line 3, in <module>
    print("hai siva")
  File "C:\Program Files\Python35\lib\idlelib\PyShell.py", line 1344, in write
    return self.shell.write(s, self.tags)
Keyboard Interrupt

Note:
solve the problems in infinite loops, we are going to use break statement

Example 2:
i=1
while True:
    print("hai siva")
    if i==5:
        break
    i=i+1

Output:
hai siva
hai siva
hai siva
hai siva
hai siva

break statement:
  • break statement is used in the looping statements.
  • when ever break statement of the loop is executed an automatically control will come out from the loop.
  • Generally we use the break statement to exit from the infinite loops.
Example:
i=1
while True:
    print("hai siva")
    if i==5:
        break
    i=i+1
else:
    print("hai krishna")

Output:
hai siva
hai siva
hai siva
hai siva
hai siva

  • we can use the else block with the while loop in python,when ever while loop condition becomes False,then only control will goto the else block.
  • if we are exiting from the while loop,by executing break statement when control will not go to the else block.
continue statement:
  • continue statements are used in loops.
  • skipping the particular iteration
  • when ever continue statement of the loop is executed can without executing the remaining part of that particular iteration when control will goto the next iteration.
Example:
i=0
while i<5:
    i=i+1
    if i==2:
        continue
    print("hai siva",i)
else:
    print("hai krishna")

Output:
hai siva 1
hai siva 3
hai siva 4
hai siva 5
hai krishna

using continue and break statements in a single program

 Example: Login form

while True:
    name=input("enter UserName: ")
    if name!= 'siva':
        continue
    password=input("Helo siva, enter your PassWord ?  ")
    if password=='krishna@143':
        break
print("Access Granted")

Output:
enter UserName: siva
Helo siva, enter your PassWord ?  krishna@143
Access Granted

Output 2:
enter UserName: abc
enter UserName: xyz
enter UserName: siva
Helo siva, enter your PassWord ?  krishna
enter UserName: siva
Helo siva, enter your PassWord ?  krishna@142
enter UserName: siva
Helo siva, enter your PassWord ?  krishna@143
Access Granted

Note:
  • Here continue and break statements are written in the if conditions,but both are working based on loops.
for  loop:
  • for loop executes the set of statements with respect to every element of the collection object.
Syntax:
                               for  variablename  in collvariable :
                                                               ----------------------
                                                               ----------------------
                                                               ----------------------
Example 1:
x=[10,20,30,40,50]
for p in x:
    print(p)

Output:
10
20
30
40
50

Example 2:
x="sivakrishna"
for p in x:
    print(p)

Output:
s
i
v
a
k
r
i
s
h
n
a

Note:
  • for loop takes string object also,but string object is not a collection object.
  • string object is a group of  characters.
Some times We are not interested blocks, simply that blocks are passed by using pass keyword. 

Example:
                if  condition :
                          pass