Skip to content
Advertisement

First occurrence of a number in python list

I have a long list which consist of two fixed possible numbers (0 and 1). e.g:

 l = [0,0,0,0,0,1,1,1,1,1,1,1]

I don’t know which number occurs first in the list but I am sure that if 0 is occurring first in the list then it will occur consecutively followed by 1, same case for 1.

I am performing some kind of action on the basis of these number conditions (0,1) but also I need to show a message before the first occurrence of 0 and 1.

First occurrence of first number (in this case 0), I have managed like this.

if l[0] == 0:
   print ('first occurrence of 0')
elif l[0] == 1:
   print ('first occurrence of 1')

I am not sure how to point out first occurrence of 1 during execution of this list.

For this example list I need result like this.

 msg before first occurrence of 0
 0
 0
 0
 0
 0
 msg before first occurrence of 1
 1
 1
 1
 1
 1
 1
 1 

Advertisement

Answer

A solution that works for more than just 0 and 1 can be based to a set containing the elements we encountered so far:

l = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
s = set()
for x in l:
    if x not in s:
        print("first occurrence of %s" % x)
        s.add(x)
    print(x)

Result:

first occurrence of 0
0
0
0
0
0
first occurrence of 1
1
1
1
1
1
1
1
Advertisement