Page 303 - Beginning Programming with Pyth - John Paul Mueller
P. 303
Notice that the square brackets are empty. List2 doesn’t contain any entries. You can create empty lists that you fill with information later. In fact, this is precisely how many lists start because you usually don’t know what information they will contain until the user interacts with the list.
2. Type len(List2) and click Run Cell.
The len() function outputs 0, as shown in Figure 13-10. When creating an application, you can check for an empty list by using the len() function. If a list is empty, you can’t perform tasks such as removing elements from it because there is nothing to remove.
3. TypeList2.append(1)andpressEnter.
4. Type len(List2) and click Run Cell.
The len() function now reports a length of 1.
5. Type List2[0] and click Run Cell.
You see the value stored in element 0 of List2, as shown in Figure 13-11.
6. Type List2.insert(0, 2) and press Enter.
The insert() function requires two arguments. The first argument is the index of the insertion, which is element 0 in this case. The second argument is the object you want inserted at that point, which is 2 in this case.
7. Type List2 and click Run Cell.
Python has added another element to List2. However, using the
insert() function lets you add the new element before the first element, as shown in Figure 13-12.
8. Type List3 = List2.copy() and press Enter.
The new list, List3, is a precise copy of List2. Copying is often used to create a temporary version of an existing list so that a user can make temporary modifications to it rather than to the original list. When the user is done, the application can either delete the temporary list or copy it to the original list.
9. Type List2.extend(List3) and press Enter.