Python Forum

Full Version: How to find something in a list using its index
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello. How do you get an item in a list using its index? I am trying to remove a number of items from a list like this:
for i in range(len(credentialsList)-3):
	credentialsList.remove(credentialsList.index(i))
but clearly I have done something wrong as I get a ValueError as index(i) expects ' i ' to be the value of a definite item in the list, so how can I do what I am trying to do?
Edit: I've just done some testing, and I've just found the (listName)[indexNumber] method / thing. Is this the answer to my question? Example:
exampleList=["example1","example2","example3"]
list.index() returns the index of the argument's value. Refer to the documentation.

x = [1,2,3]
print(x.index(2)) # Prints 1 because the number 2 is in index 1
To use an index to return a value, you need to slice the list:

x = [1,2,3]
print(x[2]) # Prints 3 because index 2 contains the number 3
If you're looking to remove everything up to the third to last item, you can do this:

x = [1,2,3,4,5,6,7]
print(x[-3:])