python list with tuple iterate for existence and get the index -
python list with tuple iterate for existence and get the index -
i have python list has tuples, want check if first element of tuple in tuples in list, manage follows:
x = [('a',1), ('b',2), ('c',3)] if 'a' in ([y[0] y in x]): //how index of tuple 'a' exist what want in index of tuple 'a' above illustration exist.
you can utilize next():
next(i in xrange(0, len(x)) if x[i][0] == 'a') note if a not found, you'll stopiteration exception. can provide default have value returned instead:
next((i in xrange(0, len(x)) if x[i][0] == 'd'), -1) demo:
>>> next(i in xrange(0, len(x)) if x[i][0] == 'a') 0 >>> next((i in xrange(0, len(x)) if x[i][0] == 'd'), -1) -1 enumerate() can used here index value:
>>> next(i i, (a, _) in enumerate(x) if == 'a') 0 >>> next((i i, (a, _) in enumerate(x) if == 'd'), -1) -1 python list list-comprehension
Comments
Post a Comment