Thursday, November 3, 2011

Python List Operation

Python List Operation:
List : Its a sequential collection of object or any element/data type is called List.
The below is the script will help you to lean about the list operation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#This program will do the list operation in doing the def functions, using the user defining function its very easy to debug the program and undestandable.


def lookup_ele(eleSerch,list):
    if eleSerch in list:
        print "element has been in the list "
    else:
        print " element",eleSerch,"is not in the list"

def print_list(list):
    i =0

    if len(list)>0:
        print "List as give below \n"
        while i<len(list):
            print i,":",list[i]
            i =i+1
    else:
        print "Empty list "


def add_list(ele,list):
    list.append(ele)
#    return list

def remove_ele(ele,list):
    if ele in list:
        print "Element is found"
        list_num = list.index(ele)
        del list[list_num]
        print ele+" elments has been deleetd from the list "
    else:
        print "element is not found"

def print_menu():
    print '================================='
    print '        List operations          '
    print ' ================================'
    print '1. Display list '
    print '2. Add element to the list '
    print '3. Remove element '
    print '4. Lookup a elements '
    print '5. Quit'
    print ' Please enter the selected value :'
    print '----------------------------------'
list = []
menu_choice = 0
print_menu()
while True:
    menu_choice = input("Type in a number (1-5): ")
    if menu_choice == 1:
        print_list(list)
    elif menu_choice == 2:
        print "Add elements "
        ele = raw_input("element: ")
        add_list(ele,list)
    elif menu_choice == 3:
        print "Remove element"
        ele = raw_input("element: ")
        remove_ele(ele,list)
    elif menu_choice == 4:
        print "Lookup element"
        eleSerch = raw_input("ele: ")
        print lookup_ele(eleSerch,list)
    elif menu_choice == 5:
        break
    else:
        print_menu()
print "Goodbye"

No comments:

Post a Comment