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,189
  • 18
  • 70
  • 115

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,440
  • 2
  • 13
  • 24
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
  • 616
  • 1
  • 5
  • 16