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.