python - How to get the index of an integer from a list if the list contains a boolean? -
i starting python.
how index of integer 1 list if list contains boolean true object before 1?
>>> lst = [true, false, 1, 3] >>> lst.index(1) 0 >>> lst.index(true) 0 >>> lst.index(0) 1 i think python considers 0 false , 1 true in argument of index method. how can index of integer 1 (i.e. 2)?
also reasoning or logic behind treating boolean object way in list? solutions, can see not straightforward.
the documentation says
lists mutable sequences, typically used store collections of homogeneous items (where precise degree of similarity vary application).
you shouldn't store heterogeneous data in lists. implementation of list.index performs comparison using py_eq (== operator). in case comparison returns truthy value because true , false have values of integers 1 , 0, respectively (the bool class subclass of int after all).
however, use generator expression , built-in next function (to first value generator) this:
in [4]: next(i i, x in enumerate(lst) if not isinstance(x, bool) , x == 1) out[4]: 2 here check if x instance of bool before comparing x 1.
keep in mind next can raise stopiteration, in case may desired (re-)raise valueerror (to mimic behavior of list.index).
wrapping in function:
def index_same_type(it, val): gen = (i i, x in enumerate(it) if type(x) type(val) , x == val) try: return next(gen) except stopiteration: raise valueerror('{!r} not in iterable'.format(val)) none some examples:
in [34]: index_same_type(lst, 1) out[34]: 2 in [35]: index_same_type(lst, true) out[35]: 0 in [37]: index_same_type(lst, 42) valueerror: 42 not in iterable
Comments
Post a Comment