-1

Below is the code. Why is it behaving so? What is the alternative?

line2 = ["a", "b","c","d","e","f","g","a","c", "d","e","g","h",]

for x in line2:
    print("X value is:", x, " and its index is:", line2.index(x))

Output is:

X value is: a  and its index is: 0
X value is: b  and its index is: 1
X value is: c  and its index is: 2
X value is: d  and its index is: 3
X value is: e  and its index is: 4
X value is: f  and its index is: 5
X value is: g  and its index is: 6
X value is: a  and its index is: 0
X value is: c  and its index is: 2
X value is: d  and its index is: 3
X value is: e  and its index is: 4
X value is: g  and its index is: 6
X value is: h  and its index is: 12

Why is it not incrementing ?. How do I resolve. I need increments of index ? Instead of index do we have something like position of X

Hyder Tom
  • 353
  • 3
  • 13

1 Answers1

4

Using that index call is very costly in each iteration, when you have it for free if you just use enumerate. Furthermore, please be aware about how index works, in that you will always only ever get the first time the value comes up.

for index, value in enumerate(line2):
     print("X value is:", value, " and its index is:", index)

In terms of cost of how your implementation, and this answer works. You can't really compare the functionality of index, with the functionality of enumerate.

Your first list is going to be O(n), naturally because you are simply iterating through the entirety of your list. However, with each call to index, that in itself is going to be O(n). That is huge in terms of inefficiency.

The enumerate iterates through your list once, providing a tuple result where the first value represents your index, and the second is simply the next value in your list, thus giving you just a O(n) complexity. Your print statement, therefore in the solution I am providing bears no cost, because you are simply just outputting the value you already have without any extra computation required.

idjaw
  • 21,992
  • 6
  • 53
  • 69
  • 1
    Perhaps also mention that `list.index` finds the first occurrence of the target, and therefore ignores any subsequent occurrences (unless the optional parameter is specified)? – inspectorG4dget Jul 25 '17 at 17:07
  • @inspectorG4dget Oh right! silly. Yes I'll add that. – idjaw Jul 25 '17 at 17:08
  • So based on my understanding, using index is Expensive. Is enumerate less expensive. – Hyder Tom Jul 25 '17 at 17:12
  • @HyderTom You can't even really compare them. Let me update my question to explain this for you. – idjaw Jul 25 '17 at 17:13
  • @HyderTom Updated. They two different functions entirely, and again, `index` is also not what you want to use in general because as explained it only gives you the index the first item it finds. – idjaw Jul 25 '17 at 17:21
  • Thank you about that. @idjaw – Hyder Tom Jul 25 '17 at 17:32