Page 313 - AI Ver 1.0 Class 9
P. 313

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 !
                  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)

                 A = [1, 2, 3]                             [1, 2, 3, 4, 5, 6, 7, 8, 9]
                 B = [4, 5, 6]

                 C = [7, 8, 9]
                 D = A + B + C

                 print(D)
                 A = [1, 2, 3]                             [1, 2, 3, 10, 20]

                 B = A + [10, 20]
                 print(B)

                 A = [1, 2, 3]                             TypeError: can only concatenate list (not "str") to list
                 B = A + "abc"

                 print(B)






                                                                                Introduction to Python  311
   308   309   310   311   312   313   314   315   316   317   318