GDog
GDog

Reputation: 165

Python List - Return Index

For the list below - "A" - I would like to return the index of the elements in "A".....except if the element in "A" equals 'SCR'. Given this list/ code:

INPUT:

A=['126.00', '9.00', '1.50', '9.50', '9.50', 'SCR', '19.00', '12.00']
B=[(A.index(i)+1) for i in A if not i=='SCR']
print(B)

OUTPUT:

[1, 2, 3, 4, 4, 7, 8]

Notice that 4 repeats.

The required output is:

[1,2,3,4,5,7,8]

Upvotes: 0

Views: 173

Answers (4)

Homer
Homer

Reputation: 429

Try:

b=[]
for i in range(len(A)):
    if A[i] != "SCR":
        b.append(i+1)

print (b)

Explanation:

  • If we just need to print the index number, we can get it via "for i in range(len(A))". Here, it's value will be: 0,1,2,3,4,5,6,7
  • With if A[i] != "SCR", we are checking if value of that index is equals to SCR, if not, then add that index value to another array - B

Upvotes: 0

Raghul Raj
Raghul Raj

Reputation: 1458

When you use list.index(), it returns the first match. So when i='9.50' you get the index of its first occurrence.

To avoid that, you can do something like this:

A=['126.00', '9.00', '1.50', '9.50', '9.50', 'SCR', '19.00', '12.00']
B=[i+1 for i in range(len(A)) if not A[i]=='SCR']
print(B)

>>[1, 2, 3, 4, 5, 7, 8]

Upvotes: 0

Mark
Mark

Reputation: 92440

You can use enumerate() to get the indices as you loop over the list:

A=['126.00', '9.00', '1.50', '9.50', '9.50', 'SCR', '19.00', '12.00']
B=[i for i, v in enumerate(A, 1) if v!='SCR']
# [1, 2, 3, 4, 5, 7, 8]

Upvotes: 4

Yash Agrawal
Yash Agrawal

Reputation: 62

Yeah it will repeat because python starts checking from the front one by one and as soon as it finds one it stops.

To get rid of this problem just delete the element at that index when found.

Also you can just do one thing--

A=['126.00', '9.00', '1.50', '9.50', '9.50', 'SCR', '19.00', '12.00'] B=[(i+1) for i in A if not i=='SCR'] print(B)

Upvotes: -1

Related Questions