Python Phrasebook

for x in numList: print x+1 print stringList[0] + ' ' + stringList[1] + ' ' + \ stringList[2] print stringList[-2] if isinstance(subList, list): print subList[2][0]

Once a list is defined, the items in the list can be accessed using a zero-based index. The first item in the list is at index zero, the second at index one, and so on.

The code example in acc_list.py demonstrates accessing all items of the list in order using the for keyword, as well as accessing the items in the list individually.

If an item in the list is a list object, you can access items in that list by adding an indexing bracket onto the end, similar to how you would access elements in a multidimensional array.

Note

Python enables you to use negative indices to access the list from the end rather than from the beginning. For example, to access the final item in a list, you would use an index of -1, an index of -2 to access the second to the last item in the list, and so on. This can be extremely useful if you have dynamic lists that change frequently.

numList = [2000, 2003, 2005, 2006] stringList = ["Essential", "Python", "Code"] mixedList = [1, 2, "three", 4] subList = ["Python", "Phrasebook", ["Copyright", 2006]] listList = [numList, stringList, mixedList, subList] #All items for x in numList: print x+1 #Specific items print stringList[0] + ' ' + stringList[1] + ' ' + \ stringList[2] #Negative indices print stringList[-2] #Accessing items in sublists if isinstance(subList, list): print subList[2][0]

acc_list.py

2001 2004 2006 2007 Essential Python Code Python Copyright

Output from acc_list.py code

Категории