Page 218 - Robotics and AI class 10
P. 218

where, item can be any value like number, string, list, etc. Examples are:

                                Commands                                            Output

           fruits = ["apple", "banana", "cherries"]               ["apple", "banana", "cherries", "melon"]
           fruits.append("melon")
           print(fruits)

           cars = ["Maruti", "Ford"]                              cars = ["Maruti", "Ford", "Honda", "Hyundai"]
           cars.append("Honda")
           cars.append("Hyundai")
           print(cars)


           #input names of 5 friends and store in list            Enter Friend Name :Amit

           friends=[]                                             Enter Friend Name: Sneha
           for i in range(5):                                     Enter Friend Name: Swati
                 nm=input("Enter Friend Name: ")                  Enter Friend Name: Sudhir
                 friends.append(nm)                               Enter Friend Name: Shashi

           print(friends)                                         ["Amit", "Sneha", "Swati", "Sudhir", "Shashi"]

           #adding a list at the end of another list              ['cat', 'dog', 'rabbit', ['tiger', 'lion']]
           pets = ['cat', 'dog', 'rabbit']
           wild = ['tiger', 'lion']
           pets.append(wild)

           print(pets)


        The insert() Function
        The insert() function is used to add a single value at a specific position in an existing list. The length of the list
        will increase by one. Syntax of the insert() function is:

          list.insert(index, value)
        Examples:

                                Commands                                        Output
                L = [10, 20, 30]                             [10, 40, 20, 30]

                L.insert(1, 40)
                print(L)

                L.insert(0, "abc")                           ['abc', 10, 40, 20, 30]
                print(L)
                a = "xyz"                                    ['abc', 10, 40, 'xyz', 20, 30]

                L.insert(3, a)
                print(L)
                L.insert(5, ["a", "b"])                      ['abc', 10, 40, 'xyz', 20, ['a', 'b'], 30]

                print(L)

              216     Touchpad Robotics & Artificial Intelligence-X
   213   214   215   216   217   218   219   220   221   222   223