0
Anyone know how .index() could be used properly? In Python?
I have a list of strings, but when I try to call any index of any strings in that list, I keep getting an error. It says whatever item I'm looking for doesn't exist. My understanding of the .index() function is that you use it to search for an item in a list by typing its place in the list, starting from 0. E = ['Zeroth place', 'sos', 'a string', 'another one'] print(E.index(1)) Output: ValueError: 1 is not in list Desired Output: 'sos'
6 Antworten
+ 7
"The index() method returns the position at the first occurrence of the specified value."
https://www.w3schools.com/JUMP_LINK__&&__python__&&__JUMP_LINK/ref_list_index.asp
That means E.index(1) is not the same as E[1].
+ 9
Az_ ,
a short sample how to use index():
names = ['bob', 'ann', 'tim', 'sue']
# find the index of 'tim'
print(names.index('tim'))
# result is 2.
# keep in mind that the first item in the list starts with index 0.
# if the item can *not* be found in the list when using index(), python will create an exception (value error) and the program will be terminated.
+ 4
The index() method returns the sequence number of the value to be searched for in the list, that is To get the result you want, you need to write:
print(E[E.index('sos')])
+ 2
The `.index()` method is used to find the index of an item in a list. The method takes one argument, which is the item you are searching for.
If the item is not found in the list, a `ValueError` is raised.
E = ['Zeroth place', 'sos', 'a string', 'another one']
#index. 0 1 2 3
print(E.index('sos'))
Output:
```
1
```
+ 1
Wow! Thank you guys! Yeah turns out I was looking for the opposite of index() - typing the place and getting the string, like E[1] or names[1]
+ 1
You have to use [1] instead of (1). Hope this helps.