Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following code, and I would like the index position of all the 1's:

mylist = ['0', '0', '1', '1', '0']

for item in mylist:
    if item is '1':
        print mylist.index(item)

Can someone explain why the output of this program is 2, 2 instead of 2, 3 ?

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
149 views
Welcome To Ask or Share your Answers For Others

1 Answer

python builtin enumerate returns a tuple of the index and the element. You just need to iterate over the enumerated tuple and filter only those elements which matches the search criteria

>>> mylist = ['0', '0', '1', '1', '0']
>>> [i for i,e in enumerate(mylist) if e == '1']
[2, 3]

Now coming back to your code. There are three issues that you need to understand

  1. Python list method index returns the position of the first occurrence of the needle in the hay. So searching '1' in mylist would always return 2. You need to cache the previous index and use it for subsequent search
  2. Your indentation is incorrect and your print should be inside the if block
  3. Your use of is is incorrect. is doesn't check for equality but just verifies if both the elements have the same reference. Though in this case it will work but its better to avoid.

    >>> index = 0
    >>> for item in mylist:
        if item == '1':
            index =  mylist.index(item, index + 1)
            print index
    
    
    2
    3
    

Finally why worry about using index when you have enumerate.

>>> for index, item in enumerate(mylist):
    if item == '1':
        print index


2
3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...