Wasi
Wasi

Reputation: 33

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 

Upvotes: 1

Views: 10270

Answers (3)

Humble_PrOgRaMeR
Humble_PrOgRaMeR

Reputation: 741

You can do it using python Recursion as well which finds first occurrence of any given number in a list. You can modify for your requirement.

Here is the following code.

def firstIndex(a, x):
l = len(a)
if l == 0:
    return -1
if a[0] == x:
    return 0
sa = a[1:]
smlist_output = firstIndex(sa, x)
if smlist_output == -1:
    return -1
else:
    return smlist_output + 1



# Main
   from sys import setrecursionlimit
   setrecursionlimit(11000)
   n=int(input()) # Read the length of an list to read the list elements from the console
   arr=list(int(i) for i in input().strip().split(' ')) # Read list elements from the console
   x=int(input()) # read the number to be found in the list
   print(firstIndex(arr, x))

input1:

5
1 2 3 4 5
4

Output1:

3

input2:

5
1 2 3 4 5
9

Output2:

-1

The function returns index as -1 if your given number does not exists in the list.

Upvotes: 0

JuniorCompressor
JuniorCompressor

Reputation: 20015

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

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117856

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

Upvotes: 8

Related Questions