Saturday, May 26, 2018

Python List

List: Generally speaking a list is a collection of objects that can contain any types of objects.
It can be an arbitrary mixture of elements like numbers, strings, other lists and so on.

Properties of Python lists:

  • The contain arbitrary objects like numbers, strings, other lists etc..
  • Elements of a list can be accessed by an index
  • They are arbitrarily nestable, i.e. they can contain other lists as sublists
  • They are mutable, i.e. the elements of a list can be changed


Below are the Example and operations on the list:

import copy

# creating a list 
itemlist = ['apple','orange','banana','grape']
itemlist_copy = itemlist # To copy a list (This is  Shallow copy)
#Adding new item to a exiting list 

itemlist.append('pepaya')
for item in itemlist:
    print(item)

Output:
apple
orange
banana
grape
pepaya

___________________________________________________________________________________________

# itemlist and itemlist_copy are equal because of Shallow copy
print(str(itemlist) +'==>'+str(itemlist_copy))

['apple', 'orange', 'banana', 'grape', 'pepaya']==>
['apple', 'orange', 'banana', 'grape', 'pepaya']

# Both lists are refering to the same object id.
print(str(id(itemlist)) + '==>' + str(id((itemlist_copy)))) 

4334167304==>4334167304

print(itemlist == itemlist_copy)
True
print(itemlist is itemlist_copy)
True

# this is deep copy
itemlist_copy = copy.deepcopy(itemlist) itemlist.append('Avocados') print(str(itemlist) +'==>'+str(itemlist_copy))

['apple', 'orange', 'banana', 'grape', 'pepaya', 'Avocados']==>
['apple', 'orange', 'banana', 'grape', 'pepaya']

 # Both lists are different, refering to different objects 
print(str(id(itemlist)) + '==>' + str(id((itemlist_copy))))
4334167304==>4334167048
# Another way to copy the list is using the list constructor,
as constructor used to create a new object.
itemlist_copy = list(itemlist)
# Here it is False because the list reference objects are different.
print("List copy constructor {}".format(itemlist is itemlist_copy))
List copy constructor False

# Here it is True because the list content are same in same order.
print("List copy constructor {}".format(itemlist == itemlist_copy))
List copy constructor True

# Both lists are refering to the same object id.
print(str(id(itemlist)) + '==>' + str(id((itemlist_copy)))) 
4334167304==>4334326280
# Adding two list even = [2,4,6,8] odd = [1,3,5,7,9] add = even + odd str1 = ['A','B'] str2 = ['C','D','E','FGH']print(sorted(even+odd))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

add.sort()
#It return None, becuase for sorting the values it needs objects and print do not create that
print(add.sort()) 
None
print(add)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

print(str1 + str2)
['A', 'B', 'C', 'D', 'E', 'FGH']

# You can also create a empty list by using the list constructor
l1 = []
l2 = list()print("List l1 {}".format(l1))
List l1 []

print("List l2 {}".format(l2))
List l2 []

if l1 == l2:
print("the list are equal")
the list are equal
# List constructor automatically create a list when pass a string print(list("This list is created using constructor")) ['T', 'h', 'i', 's', ' ', 'l', 'i', 's', 't', ' ', 'i', 's', ' ', 'c', 'r', 'e', 'a', 't',
'e', 'd', ' ', 'u', 's', 'i', 'n', 'g', ' ', 'c', 'o', 'n', 's', 't', 'r', 'u', 'c', 't', 
'o', 'r']


# Nested List
even = [2,4,6,8]
odd = [1,3,5,7,9]
number = [even,odd]

print(number)
[[2, 4, 6, 8], [1, 3, 5, 7, 9]]

for list_set in number:
    print(list_set)                 # Printing even and odd list    for list_evement in list_set:
        print(list_evement)         # Printing even and odd list elements
[2, 4, 6, 8]
2
4
6
8
[1, 3, 5, 7, 9]
1
3
5
7
9

Tuesday, May 22, 2018

Common Sequence Operations

The operations in the following table are supported by most sequence types, both mutable and immutable.


OperationResultNotes
x in sTrue if an item of s is equal to x, else False(1)
x not in sFalse if an item of s is equal to x, else True(1)
s + tthe concatenation of s and t(6)(7)
s * n or n * sequivalent to adding s to itself n times(2)(7)
s[i]ith item of s, origin 0(3)
s[i:j]slice of s from i to j(3)(4)
s[i:j:k]slice of s from i to j with step k(3)(5)
len(s)length of s
min(s)smallest item of s
max(s)largest item of s
s.index(x[, i[, j]])index of the first occurrence of x in s (at or after index i and before index j)(8)
s.count(x)total number of occurrences of x in s
Below are the examples for the above tables.


x = 'Apple's = 'She eats Apple 't = 'in the morning'n = 2i = 10j = 20k = 21
print(x in s)
print(x not in s)
print(s + t)
print(x*n)
print(s[i])
print(s[i:j])
print(s[i:j:k])
print(len(s))
print(min('a','b'))
print(max('a','b'))
print(s.index(str(x)))
print(s.count('e'))


Output : 

True
False
She eats Apple in the morning
AppleApple
p
pple 
p
15
a
b
9
3



String Formatting

String formatting is important in any programming language below are 
some sample examples in python, these examples are covering most the string 
formatting in python.


bld_no = 200
print("I live in building " +"P"+str(bld_no))

Output : I live in building P200

# replacement fields
print("I live in building P{0}".format(bld_no))

Output : I live in building P200

print("There are {0} days in the month {1}, {2}, {3}, {4}, {5}, {6}, {7}
       ".format(31, "Jan","Mar","May","Jul","Aug","Oct","Dec" ))
Output : There are 31 days in the month Jan, Mar, May, Jul, Aug, Oct, Dec

print("Jan: {2} Feb: {0} Mar: {2} Apr: {1}"      "May - {2} Jun - {1} Jul - {2} Aug {2} Sep {1}"      "Oc - {2} Nav - {1} Dec - {2}".format(28,30,31))
Output : Jan: 31 Feb: 28 Mar: 31 Apr: 30May - 31 Jun - 30 Jul - 31 Aug 31 Sep 30Oc - 31 Nav - 30 Dec - 31
print("I live in building P %d" %bld_no)

Output : I live in building P237
print("I live in building P %d at %d floor near %s" %(bld_no,1,"albany dr")) 

Output : I live in building P 200 at 1 floor near albany dr
data = "1:A, 2:B, 3:C, 4:D, 5:E, 6:F, 7:G, 8:H"print(data[::5])

Output : 12345678

Python For Loop with Example

for i in range(1,5):
    print("i is now {}".format(i))

i is now 1
i is now 2
i is now 3
i is now 4

_______________________________________________________________________________

string = '123,456,789,123,456,789,000'cleannumber = ''for i in range(0,len(string)):
    print("is is now {}".format(string[i]))
    if string[i] in '0123456789':
        cleannumber = cleannumber + string[i]
print(string)print(cleannumber)
 i is now 1
 i is now 2
 i is now 3
 i is now ,
 i is now 4
 i is now 5
 i is now 6
 i is now ,
 i is now 7
 i is now 8
 i is now 9
 i is now ,
 i is now 1
 i is now 2
 i is now 3
 i is now ,
 i is now 4
 i is now 5
 i is now 6
 i is now ,
 i is now 7
 i is now 8
 i is now 9
 i is now ,
 i is now 0
 i is now 0
 i is now 0
123,456,789,123,456,789,000
123456789123456789000

_________________________________________________________________________________

string = '123,456,789,123,456,789,000'
cleannumber = ''for c in string: if c in '0123456789': cleannumber = cleannumber + c print(cleannumber) 123456789123456789000

__________________________________________________________________________________

for name in ("A","M","M","Y"):
    print("Current name is :{}".format(name))
Current name is :A
Current name is :M
Current name is :M
Current name is :Y
__________________________________________________________________________________
for i in range(0,100,5): #step print(i) 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95

__________________________________________________________________________________
#print a table from 2 to 10 for i in range(1,11): for j in range(1,11): print("{1} times {0} is {2}".format(j,i,j*i)) print("******************************************") 1 times 1 is 1 1 times 2 is 2 1 times 3 is 3 1 times 4 is 4 1 times 5 is 5 1 times 6 is 6 1 times 7 is 7 1 times 8 is 8 1 times 9 is 9 1 times 10 is 10 ****************************************** 2 times 1 is 2 2 times 2 is 4 2 times 3 is 6 2 times 4 is 8 2 times 5 is 10 2 times 6 is 12 2 times 7 is 14 2 times 8 is 16 2 times 9 is 18 2 times 10 is 20 ****************************************** 3 times 1 is 3 3 times 2 is 6 3 times 3 is 9 3 times 4 is 12 3 times 5 is 15 3 times 6 is 18 3 times 7 is 21 3 times 8 is 24 3 times 9 is 27 3 times 10 is 30 ****************************************** 4 times 1 is 4 4 times 2 is 8 4 times 3 is 12 4 times 4 is 16 4 times 5 is 20 4 times 6 is 24 4 times 7 is 28 4 times 8 is 32 4 times 9 is 36 4 times 10 is 40 ****************************************** 5 times 1 is 5 5 times 2 is 10 5 times 3 is 15 5 times 4 is 20 5 times 5 is 25 5 times 6 is 30 5 times 7 is 35 5 times 8 is 40 5 times 9 is 45 5 times 10 is 50 ****************************************** 6 times 1 is 6 6 times 2 is 12 6 times 3 is 18 6 times 4 is 24 6 times 5 is 30 6 times 6 is 36 6 times 7 is 42 6 times 8 is 48 6 times 9 is 54 6 times 10 is 60 ****************************************** 7 times 1 is 7 7 times 2 is 14 7 times 3 is 21 7 times 4 is 28 7 times 5 is 35 7 times 6 is 42 7 times 7 is 49 7 times 8 is 56 7 times 9 is 63 7 times 10 is 70 ****************************************** 8 times 1 is 8 8 times 2 is 16 8 times 3 is 24 8 times 4 is 32 8 times 5 is 40 8 times 6 is 48 8 times 7 is 56 8 times 8 is 64 8 times 9 is 72 8 times 10 is 80 ****************************************** 9 times 1 is 9 9 times 2 is 18 9 times 3 is 27 9 times 4 is 36 9 times 5 is 45 9 times 6 is 54 9 times 7 is 63 9 times 8 is 72 9 times 9 is 81 9 times 10 is 90 ****************************************** 10 times 1 is 10 10 times 2 is 20 10 times 3 is 30 10 times 4 is 40 10 times 5 is 50 10 times 6 is 60 10 times 7 is 70 10 times 8 is 80 10 times 9 is 90 10 times 10 is 100 ****************************************** # Print the number from 1..100 divisible for 3

__________________________________________________________________________________
for i in range(3,35,3):
    print(i)

3
6
9
12
15
18
21
24
27
30
33

Break and Continue


continue : This statement jump to the loop without executing the next line of codes.

break : Break generally use for coming outside the loop without completing all the iterations.

Example:

item_list = ['apple','orange','banana','spam','grapes']

for item in item_list:
    if item == 'spam':
        continue
    print(item)
print("------------------------------")
for item in item_list:
    if item == 'spam':
        break
    print(item)

# Print all numbers divisible by 7 between 0 - 100 until you find a a number divisible by 11

for i in range(0, 100, 7):
    print(i)
    if i > 0 and i % 11 == 0:
        break


Output :

apple
orange
banana
grapes
------------------------------
apple
orange
banana
0
7
14
21
28
35
42
49
56
63
70
77

Program to check valid IP addresses

Create a program that takes an IP address and print out the segment it contains.
Also, check if the format of the IP address is correct.

def validate_ip(ip):
    ln = ip.split('.')
    if len(ln) != 4:
        return False    for digit in ln:
        if not digit.isdigit():
            return False        i = int(digit)
        if i < 0 or i > 255:
            return False    return True
result = validate_ip(input("Please enter a IP address : "))
if result == True:
    print('Entered IP is correct')
else:
    print('Invalid IP')

Print statement

Print statement in python takes 5 parameters.




    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Example: Print name and age in a file separated with | and ending with *

name = 'Your Name'
age = 22print(name,age,sep='|',end='*',file=open('file_path', 'w'), flush=False)

Output:

Your Name|22*

if can also change the default file = sys.stdout as:

import sys
sys.stdout = open('File_Path', 'w')

Program to check valid IP addresses