faceless
faceless

Reputation: 506

Don't understand a Python List Index

So, I don't completely understand .index() and have been messing around with a block of code to try and understand it, but it's still not clicking with me.

When messing with this list:

myList = [5024,3,True,6.5,12,1,2,2,2]
print(myList)
print(myList.index(2))

It comes out printing: 6 Where is this 6 coming from?

As another example:

myList = [5024,3,True,6.5,12,1,2,2,2]
print(myList)
print(myList.index(4))

This is troubleshooted as: 4 is not in list

but when printing:

myList = [5024,3,True,6.5,12,1,2,2,2]
print(myList)
print(myList.index(1))

prints: 2

This is what I don't understand. Is the program counting how many occurrences of 1 there are in this list? If that's the case, when trying to .index(2) in this list, it comes printing out 6 instead of 5.

Whats going on here?

Upvotes: 1

Views: 867

Answers (2)

midori
midori

Reputation: 4837

Data Structures - read this article if you need more info.

list.index(x)

Return the index in the list of the first item whose value is x. It is an error if there is no such item.

You can access elements in your list by index. Indexes start from 0. Assuming you have a list, let's see indexes of the elements:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] list_of_nums

[0 1 2 3 4 5 6 7 8 9 ] indexes

So if you use list_of_nums.index(3) it will return an index of the first occurrence of the element with value 3 in the list and it's 2.

In your case myList.index(2) returns an index of the first occurrence of the element with value 2 which is 6.

myList.index(4) returns '4 is not in list' because there is no such an element with value 4 in your list. myList.index(1) returns an element with value True because it's the first occurrence of the element with value 1, True == 1 and False == 0.

So you can find index of any element in your list if you know its value. Also you can use indexes to get value like this: myList[1] - 3

I hope now it's more clear.

Upvotes: 1

heemayl
heemayl

Reputation: 42137

True is being interpreted as 1.

As myList.index(value) returns the first index of the value so you are getting the values:

>>> myList = [5024,3,True,6.5,12,1,2,2,2]
>>> myList.index(2)
6
>>> myList.index(1)
2

If you want to find the value at a particular index, use:

myList[index]

Upvotes: 4

Related Questions