0

For a list ["foo", "bar", "baz", "bar"].index('bar') what's the cleanest way to get its index in a loop in Python? Note that .index() returns only the first element which matches in the list

for file_id in file_ids:
      file_id_index = file_ids.index(file_id)
Gerald Hughes
  • 5,771
  • 20
  • 73
  • 131

2 Answers2

1

A simple list comprehension

a = ["foo", "bar", "baz", "bar"]
x = "bar"
found = [idx for idx, item in enumerate(a) if item == x]

print(found)
Anonta
  • 2,500
  • 2
  • 15
  • 25
1

You can get all indexs of specific element in a list.

a = ["foo", "bar", "baz", "bar"]

b = [item for item in range(len(a)) if a[item] == 'bar']
print b
Solomon
  • 626
  • 1
  • 5
  • 16