Skip to content Skip to sidebar Skip to footer

Beginner Python List Complehension, Look Up Index

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.ind

Solution 1:

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 inenumerate(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)
            printindex23

Finally why worry about using index when you have enumerate.

>>> forindex, item in enumerate(mylist):
    if item == '1':
        printindex23

Solution 2:

It's because mylist.index(item) is a function that looks up the index of the first time item appears in the array; that is you could call mylist.index('1') and immediately get index 2 without even putting it in a loop.

You want to do something like, where enumerate starts a zero-based index while going through the loop:

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

for i,item in enumerate(mylist):
    ifitem== '1':
        print i

Post a Comment for "Beginner Python List Complehension, Look Up Index"