How to Access Lists in Python
After you create a list using Python, you want to access the information it contains. An object isn’t particularly useful if you can’t at least access the information it contains. The following steps describe how to do just that.
1Open a Python Shell window.
You see the familiar Python prompt.
2Type List1 = [One, 1, Two, True] and press Enter.
Python creates a list named List1 for you.
3Type List1 and press Enter.
You see the value 1 as output. 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.
4Type List1[1:3] and press Enter.
You see a range of values that includes two elements. 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.
5Type List1[1:] and press Enter.
You see all the elements, starting from element 1 to the end of the list. A range can have a blank ending number, which simply means to print the rest of the list.
6Type List1[:3] and press Enter.
Python displays the elements from 0 through 2. Leaving the start of a range blank means that you want to start with element 0.
7Close the Python Shell window.
Even though it’s really confusing to do so, you can use negative indexes with Python. Instead of working from the left, Python will work from the right and backward. For example, if you have List1 = [“One”, 1, “Two”, True] and type List1[-2], you get Two as output. Likewise, typing List[-3] results in an output of 1. The rightmost element is element -1 in this case.