indexing - Python index issue -
this question has answer here:
- accessing index in python 'for' loops 13 answers
- how find occurrences of element in list? 8 answers
- finding indices of matching elements in list in python 3 answers
below code. why behaving so? alternative?
line2 = ["a", "b","c","d","e","f","g","a","c", "d","e","g","h",] x in line2: print("x value is:", x, " , index is:", line2.index(x))
output is:
x value is: , index is: 0 x value is: b , index is: 1 x value is: c , index is: 2 x value is: d , index is: 3 x value is: e , index is: 4 x value is: f , index is: 5 x value is: g , index is: 6 x value is: , index is: 0 x value is: c , index is: 2 x value is: d , index is: 3 x value is: e , index is: 4 x value is: g , index is: 6 x value is: h , index is: 12
why not incrementing ?. how resolve. need increments of index ? instead of index have position of x
using index
call very costly in each iteration, when have free if use enumerate. furthermore, please aware how index works, in ever first time value comes up.
for index, value in enumerate(line2): print("x value is:", value, " , index is:", index)
in terms of cost of how implementation, , answer works. can't compare functionality of index
, functionality of enumerate
.
your first list going o(n)
, naturally because iterating through entirety of list. however, each call index
, in going o(n)
. huge in terms of inefficiency.
the enumerate
iterates through list once, providing tuple result first value represents index, , second next value in list, giving o(n)
complexity. print
statement, therefore in solution providing bears no cost, because outputting value have without computation required.
Comments
Post a Comment