Page 252 - Ai_V1.0_Class9
P. 252

Each element can be accessed by using:
                 listname[index number]

                                                Commands                                Output

                             print(L1[0])                                      P
                             print(L1[3])                                      H
                             print(L1[-3])                                     H
                             print(L1[-1])                                     N
                             print(L1)      #print complete list               ['P', 'Y', 'T', 'H', 'O', 'N']

                             print(L1[0], L1[4])                               P O

              Traversing a List
              Traversing means visiting each element and processing it as required by a program. We use a loop to traverse a
              list. There are different ways of visit each element as shown below:

                                                 Commands                                         Output

                    L1=['P', 'Y', 'T', 'H', 'O', 'N']                                     P ! Y ! T ! H ! O ! N !
                    for eachvalue in L1:
                        print(eachvalue, end="!")
                    L1=['P', 'Y', 'T', 'H', 'O', 'N']                                     P ! Y ! T ! H ! O ! N !
                    for indexno in range(len(L1)):
                        print(L1[indexno],end="!")
                    #The above code is equivalent to:                                     P ! Y ! T ! H ! O ! N !
                    L1=['P', 'Y', 'T', 'H', 'O', 'N']
                    print(L1[0], L1[1], L1[2], L1[3], L1[4], L1[5],
                    sep="!",end="!")
                    #To print the index number of each element in a list                  0 ! 1 ! 2 ! 3 ! 4 ! 5 !
                    L1=['P', 'Y', 'T', 'H', 'O', 'N']
                    for indexno in range(len(L1)):
                        print(indexno,end="!")

              Using + Operator with List

              The + operator is used to concatenate the list with another list. Remember that both the operands on either side
              of the + operator have to be a list only otherwise it gives an error. For example,

                                  Commands                                          Output

                    A = [1, 2, 3]                            [1, 2, 3, 4, 5, 6]
                    B = [4, 5, 6]
                    C = A + B
                    print(C)

                    A = [1, 2, 3]                            [4, 5, 6, 1, 2, 3]
                    B = [4, 5, 6]
                    B += A
                    print(B)




                    250     Artificial Intelligence Play (Ver 1.0)-IX
   247   248   249   250   251   252   253   254   255   256   257