1

I have interesting question: Let's assume that we have lst = [1,2,3,4,5,5,5,5,5,6,7,8] I am interested on saying to if statement only return result of 3rd 5.
for example:

for i in range(0,lent(lst)):
   if lst[i]==5:
      print(i,"is index of 1st 5")
      break

but how to say ask if to show 3rd 5's index without additional parameter or listing?

FrankNaive
  • 27
  • 2
  • 2
    Anyway, here you could just keep a *count* fo the number of five's you've seen, and then break on the condition `list[i] == 5 and count == 2`. Note, that means you are seeing the 3rd 5, since you've already counted 2 – juanpa.arrivillaga Apr 24 '19 at 22:43
  • 3
    If I told you the list of numbers one at a time, how would you solve this problem by hand? You should describe these steps **in words** using whatever written language you know best. Once you have a good understanding of how to solve the problem yourself, it will be easier to tell the computer how to do it. – Code-Apprentice Apr 24 '19 at 22:47

4 Answers4

0

This should fit your needs

counter = 0
for item in lst:
    if item == 5:
        counter += 1
    if counter >= 3:
        break
Roqux
  • 608
  • 1
  • 11
  • 25
0

You can use enumerate on the list and get all the indices of the required element then you get whatever index you want

lst = [1,2,3,4,5,5,5,5,5,6,7,8]
occurances = [idx for idx, val in lst if val == 5]
occurances[0] # first occurance
occurances[1] # second occurance
occurances[2] # third occurance 
Sameh K. Mohamed
  • 2,323
  • 4
  • 29
  • 55
0

juanpa.arrivillaga already pointed the usual solution out.
However, with e.g. numpy you could do also another way:

import numpy as np
lst = np.array([1,2,3,4,5,5,5,5,5,6,7,8])

cnt5 = (lst==5).cumsum()
np.arange(len(lst))[cnt5==3][0]

# 6

cnt5 is the cumulative sum of the boolean array, which is True only at indices where lst has a 5, i.e.: it's an array of the counters of lst's 5's.
Then you only need the index where this array is 3.

SpghttCd
  • 10,510
  • 2
  • 20
  • 25
0

Use a nested if statement under the if inside the for loop.

Therefore, your code should be like this:

count = 0
for i in range(0,len(lst)):
   if lst[i] == 5:
      count += 1
      if count == 3:
         print(i,"is index of 3rd 5")
         break
Dharman
  • 30,962
  • 25
  • 85
  • 135
NameError
  • 206
  • 1
  • 3
  • 19