Page 326 - Artificial Intellegence_v2.0_Class_9
P. 326

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)
                        Commands                                    Output

                   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. 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]
              print(l1 == l2)                              #True

              print(l1 > l2)                               #False
              print(l1 == l3)                              #False

              print(l1 == l4)                              #False
              print([1, 2, 6] < [1, 2, 5]) #False

              print([1, 2, 6] != [1, 2, 5]) #True
              print([1, 2, 6] > [1, 2, 5]) #True

        Slicing a List
        Slicing a list means accessing a specific portion of a list. This can be done by using a range of values with start
        index number, end index number with colon in between. We can use both forward index and backward index to
        specify the range of slicing a list. Some important points to consider to do slicing in a list are:
           • Elements from beginning to a range - list[ : index]  or [ : -index]
           • Elements from specific Index till the end - list[index:]


              324     Touchpad Artificial Intelligence (Ver. 2.0)-IX
   321   322   323   324   325   326   327   328   329   330   331