indexing - Python index issue -


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

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -