Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 120 - 2615_KEC
P. 120

    max(): This function returns the largest item in the list.
                          min(): This function returns the smallest item in the list.

                          sum(): This function returns the sum of all items in the list (useful for lists of numbers).
                          sorted(): This function returns a new list containing all items from the original list in sorted
                        order without modifying the original list.
                          reversed(): This function returns an iterator that accesses the given list in reverse order.
                          append(x): This function adds item x to the end of the list.

                          extend(iterable): This function appends all items from the given iterable to the list.
                          insert(i, x): This function inserts item x at index i.
                          remove(x): This function removes the first occurrence of x from the list.

                          pop([i]): This function removes and returns the item at index i. If no index is specified, it removes
                        and returns the last item.
                          clear(): This function removes all items from the list, leaving it empty.
                      Program 17: A program to demonstrate the use of various built-in list methods.

                          Program17.py

                       File  Edit  Format   Run    Options   Window    Help

                       robot_list = ["Pepper", "Spot", "Nao"]
                       print("Initial list:", robot_list)
                       robot_list.append("ASIMO")
                       print("After append:", robot_list)
                       robot_list.extend(["Atlas", "Sophia"])
                       print("After extend:", robot_list)
                       robot_list.remove("Nao")
                       print("After remove 'Nao':", robot_list)
                       last_robot = robot_list.pop()
                       print("After pop:", robot_list)
                       print("Removed robot:", last_robot)
                       robot_list.insert(1, "Robonaut")
                       print("After insert at index 1:", robot_list)
                       print("Count of 'Pepper':", robot_list.count("Pepper"))
                       print("Index of 'Spot':", robot_list.index("Spot"))
                       robot_list.sort()
                       print("After sort:", robot_list)
                       robot_list.reverse()
                       print("After reverse:", robot_list)
                       robot_list.clear()
                       print("After clear:", robot_list)

                       118  Premium Edition-VIII

| 115 116 117 118 119 120 121 122 123 124 125 |