image
image
image

Accessing Elements from a List

image

In programming and in Python specifically, the first time is always indexed zero. For a list of five items we will access them from index0 to index4. Failure to access the items in a list in this manner will create index error. The index is always an integer as using other number types will create a type error. For nested lists, they are accessed via nested indexing.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

––––––––

image

list_mine=[‘b’,’e’,’s’,’t’]

print(list_mine[0])   #the output will be b

print(list_mine[2])   #the output will be s

print(list_mine[3])   #the output will be t

Exercise

Given the following list:

your_collection=[‘t’,’k’,’v’,’w’,’z’,’n’,’f’]

a. Create a program in Python to display the second item in the list

b. Create a program in Python to display the sixth item in the last

c. Create a program in Python to display the last item in the list.