Page 317 - AI Ver 1.0 Class 9
P. 317

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 extend( ) Function
            The extend() Function is used to append multiple values at a time in a list. Syntax of the extend() function is:

               list.extend(iterable value)
            where iterable value can be a list. Examples are:

                                       Commands                             Output

                              n=[1,2,3,4]                     [1, 2, 3, 4, 5]
                              m=[5]
                              n.extend(m)

                              print(n)
                              pets = ['cat', 'dog',  ['cat', 'dog', 'rabbit', 'tiger', 'lion']
                              'rabbit']

                              wild=['tiger', 'lion']
                              pets.extend(wild)
                              print(pets)






                                                                                Introduction to Python  315
   312   313   314   315   316   317   318   319   320   321   322