cubflier cubflier - 1 month ago 18
Python Question

Python - Return integer value for list enumeration

Is there a cleaner way to get an integer value of the position of a list item in this code:

a = ['m', 'rt', 'paaq', 'panc']
loc = [i for i, x in enumerate(a) if x == 'rt']
loc_str = str(loc).strip('[]')
loc_int = int(loc_str)
id_list = a[loc_int + 1:]
print id_list


Returns all items after 'rt' as a list ['paaq', 'panc']

Answer

Yes, use list.index().

a = ['m', 'rt', 'paaq', 'panc']
id_list = a[a.index('rt')+1:]
assert id_list == ['paaq', 'panc']

Or, to minimally change your program:

a = ['m', 'rt', 'paaq', 'panc']
loc_int = a.index('rt')
id_list = a[loc_int + 1:]
print id_list

References: