Python Forum
How to find something in a list using its index
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to find something in a list using its index
#1
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"]
Reply
#2
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:])
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Program to find Mode of a list PythonBoy 6 1,075 Sep-12-2023, 09:31 AM
Last Post: PythonBoy
Thumbs Down I hate "List index out of range" Melen 20 3,307 May-14-2023, 06:43 AM
Last Post: deanhystad
  find random numbers that are = to the first 2 number of a list. Frankduc 23 3,198 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  Find (each) element from a list in a file tester_V 3 1,205 Nov-15-2022, 08:40 PM
Last Post: tester_V
  read a text file, find all integers, append to list oldtrafford 12 3,519 Aug-11-2022, 08:23 AM
Last Post: Pedroski55
  IndexError: list index out of range dolac 4 1,901 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  find some word in text list file and a bit change to them RolanRoll 3 1,522 Jun-27-2022, 01:36 AM
Last Post: RolanRoll
  How to find the second lowest element in the list? Anonymous 3 1,999 May-31-2022, 01:58 PM
Last Post: Larz60+
  IndexError: list index out of range Anldra12 2 1,437 May-03-2022, 01:39 PM
Last Post: Anldra12
  Python Program to Find the Total Sum of a Nested List vlearner 8 4,896 Jan-23-2022, 07:20 PM
Last Post: menator01

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020