-4

I have:

name = ["a","a","b","c","a","b","c","d","d","e","e","f"]

and I want to have index numbers of "a".

for i in range(0,len(name)):
    a = name.index("a",i,len(name))    
    print(a)


0
1
4
4
4
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-29-db6d8b18d6e6> in <module>
      1 for i in range(0,len(name)):
----> 2     a = name.index("a",i,len(name))
      3     print(a)

ValueError: 'a' is not in list

I get this error.

  • Why does your code have `name.index(...)` but the error message says `malik.index(...)`? – mkrieger1 Nov 05 '20 at 17:45
  • 1
    From the [documentation](https://docs.python.org/3/tutorial/datastructures.html), `list.index()` _"return(s) zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item."_ When it reaches the location of the error, there are no more `"a"` in the list beyond index `i`. Why are you surprised that it behaves as documented? – Pranav Hosangadi Nov 05 '20 at 17:45

5 Answers5

3

Getting index numbers of "a"

Using a for loop

name = ["a","a","b","c","a","b","c","d","d","e","e","f"]
i = 0 # used to store index
for n in name:
    if n == 'a':
        print(i) # print the index of found value
    i += 1

Using list comprehension

$ name = ["a","a","b","c","a","b","c","d","d","e","e","f"]
$ [i for i, v in enumerate(name) if v == "a"]

[0, 1, 4]

Where i, v are index and value from name list respectively

Modifying your original code

for i in range(0,len(name)):
    if "a" in name[i:]: # added an if statement to check if a exist in the sublist
        a = name.index("a",i,len(name))    
        print(a)

Why the index error

Lets take a look at whats happening with the list's index function.

index(...) method of builtins.list instance
    L.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.

We can see the list takes in value, with 2 optional parameters start and stop start and stop check a sublist of the given list L. If the value does not exist in L, then we get an index error. For example, given your code:

name = ["a","a","b","c"]

for i in range(0,len(name)):

    a = name.index("a",i,len(name))    
    print(a)

index will look for "a" for each sublist in this order

  • ["a","a","b","c"]
  • ["a","b","c"]
  • ["b","c"]

The third list will return an error because "a" is no longer in the list.

0

You can loop through the string:

name = ["a","a","b","c","a","b","c","d","d","e","e","f"]
idx = [i for i in range(len(name)) if name[i] == 'a']
print(idx)

output

[0, 1, 4]
Mike67
  • 11,175
  • 2
  • 7
  • 15
0

if you want all the indices of element in list, you can use this:

name = ["a","a","b","c","a","b","c","d","d","e","e","f"]

indices = [iter for iter,item in enumerate(name) if item=="a"]
print(indices)

output:

[0, 1, 4]
Yossi Levi
  • 1,258
  • 1
  • 4
  • 7
0

index function searches for a given element from the start of the list and returns the lowest index where the element appears.

list.index() function returns error when it can't find

start (Optional) - The position from where the search begins. end (Optional) - The position from where the search ends.

len(name) is 12 you are getting error when loop runs function name.index("a", 5, 12). and in this range there is not "a" character in list.

You can use try catch to handle error

for i in range(0, len(name)):
    try:
        a = name.index("a", i, len(name))
        print(a)
    except ValueError as err:
        print(err)
-1

You could use enumerate and an if statement:

name = ["a","a","b","c","a","b","c","d","d","e","e","f"]
for i in enumerate(name):
    if i[1]=="a": print(i[0])
J.Massey
  • 88
  • 1
  • 7