First occurance of a number in python list
I am new to python so please sorry if it is really very silly kind of question.
I have a long list which consist of two fixed possible numbers (0 and 1).
e.g:
list = [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 occuring first in the list than it will consecutive occurance follwing by 1, same case for 1.
I am performing some kind of action on basis of these number conditions (0,1) but also i need to show a msg before first occurance of 0 and 1.
First occurance of first number (in this case 0), i have managed like this.
if list[0] == 0:
print ('first occurance of 0')
elif list[0] == 1:
print ('first occurance of 1')
I am not sure how to point out first occurance of 1 during execution of this list.
For this example list i need result like this.
msg before first occurance of 0
0
0
0
0
0
msg before first occurance of 1
1
1
1
1
1
1
1
Solution 1:
Use index
to find the first occurrence of an item in a list
>>> l = [0,0,0,0,0,1,1,1,1,1,1,1]
>>> l.index(0)
0
>>> l.index(1)
5
Solution 2:
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