Page 253 - Ai_V1.0_Class9
P. 253

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)

                      l1 = [1, 2, 3]                            [1, 2, 3, 4, 5, 6, 7, 8, 9]
                      l3 = [7, 8, 9]
                      newlist = l1 + [4, 5, 6] + l3
                      print(newlist)


                 Using * Operator with List
                 The * operator is used to replicate a list by a specific number of times. With * operator, one operand has to be a
                 list and the other should only be an integer, otherwise it will give an error. For example,
                                Commands                                    Output

                            A = [1, 2, 3]         [1, 2, 3, 1, 2, 3, 1, 2, 3]
                            B = A * 3
                            print(B)
                            X = 5                 [5, 5, 5]

                            A = [X] * 3
                            print(A)
                            name = "Amit"         ['Amit', 'Amit', 'Amit', 'Amit']
                            L1= [name] * 4
                            print(L1)
                            name = "Amit"         TypeError: can't multiply sequence by non-int of type 'str'
                            L1 = [name] *
                            "a"


                 Comparing the Lists
                 The comparison of the lists is done using comparison operators >, <, >=, <=, != and ==. These operators
                 compare the elements in lexicographical order (alphabetically order). For example, if corresponding elements
                 are same, it goes to the next element, and so on until it finds elements that differ. For example,

                       l1 = [1, 2, 3]
                       l2 = [1, 2, 3]

                       l3 = [1, 2, [3]]
                       l4 = [1.0, 2.0, 3,0]
                                                                                        Introduction to Python  251
   248   249   250   251   252   253   254   255   256   257   258