Page 409 - Ai_417_V3.0_C9_Flipbook
P. 409

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"


                                 Task
                                                                                 #Experiential Learning

                     Write the output of the following statements:

                     1. print(2*"abc")
                     2. print('abc'*2)
                     3. print(2*'abc'*3)



                                                                                        Introduction to Python  407
   404   405   406   407   408   409   410   411   412   413   414