Page 300 - Beginning Programming with Pyth - John Paul Mueller
P. 300
1. Type List1 = [“One”, 1, “Two”, True] and click Run Cell. Python creates a list named List1 for you.
2. Type List1[1] and click Run Cell.
You see the value 1 as output, as shown in Figure 13-5. The use of a number within a set of square brackets is called an index. Python always uses zero-based indexes, so asking for the element at index 1 means getting the second element in the list.
3. Type List1[1:3] and click Run Cell.
You see a range of values that includes two elements, as shown in Figure 13-6. When typing a range, the end of the range is always one greater than the number of elements returned. In this case, that means that you get elements 1 and 2, not elements 1 through 3 as you might expect.
4. Type List1[1:] and click Run Cell.
You see all the elements, starting from element 1 to the end of the list, as shown in Figure 13-7. A range can have a blank ending number, which simply means to print the rest of the list.
5. Type List1[:3] and click Run Cell.
Python displays the elements from 0 through 2. Leaving the start of a range blank means that you want to start with element 0, as shown in Figure 13-8.
FIGURE 13-5: Make sure to use the correct index number.
FIGURE 13-6: Ranges return multiple values.
FIGURE 13-7: Leaving the ending number of a range blank prints the rest of the list.