# List index out of range!

i tried running the following code -

``````numbers = [1, 2, 9,]
num =[2,4,5]
for i in num:
print(numbers[i])
``````

I am getting index error telling me that the list index is out of range . Can anyone kindly help me with this? Not able to understand this error.

Two different access methods. The `for` iteration variable is a value in the list. The print numbers statement is accessing an index. Canâ€™t mix things like this.

5 Likes

oh, that means if I use range as in the following code its accessing an indexâ€¦

``````numbers = [1, 2, 9,]
numbers1 =[2,4,5]
list1 = [numbers[i] for i in range(len(numbers1))]
print(list1)
``````

to access an index should we always be using range?

Yes. If you want to access elements in a list by their index (in a loop), use `range`.

2 Likes

oh, Okay, thank you so much.

2 Likes

Thank you so much Sir.

2 Likes

Note: If you only wish to access the values without changing them, then use the read only loop,

``````for value in the_list:
``````

Then we donâ€™t need to mess around with the indices. We only need the index if we wish to mutate that elementâ€™s value.

What you have in the first post is still a valid approach except there is no index 4 or 5 in the numbers, only `0, 1, and 2`. The range based on list length is that sequence. TBH, I glanced over it too fast to see what you were actually doing.

``````num = range(len(numbers))  =>  [0, 1, 2]
``````

Accessing by a list of indices is something we may find ourselves doing in a large list where we have located the indices of a subset of values from the list.

Say we have a long list of numbers and we want the index of every number that is a multiple of 4. We would run an algorithm to ferret out the values and store their index, and then we can later access only those values in the larger list.

``````numbers = [1,11,12,15,16,25,28,31,36,41,44,53,56]

nums = []

for i in range(len(numbers)):
if numbers[i] % 4 == 0:
nums.append(i)
``````

Then later,

``````for i in nums:
print (numbers[i], end=", ")
print ()

# 12, 16, 28, 36, 44, 56,``````
2 Likes

okay, now I got it why we use â€śrangeâ€ť.
Thank you so much for clearing my doubt.

1 Like