Home > Blockchain >  Print location of specific value of list
Print location of specific value of list

Time:05-09

I want to print the location of specific values in a list. The following code prints out the location where the condition is met the first time, almost as many times as the condition is met instead of printing out every single location.

The code:

numlist=[4,4,4,4,4,3,3,3,3,2,1,1,1,1,1,1,1,1]
for i in numlist:
    if i==4:
        print(numlist.index(1))

Prints out:

10
10
10
10
10

When what I expect is:

10
11
12
13
14
15
16
17

CodePudding user response:

Here is a quick one-liner using a list comprehension:

def find_indicies(num_list,val):
    return [i for i in range(len(numlist)) if num_list[i]==val]

CodePudding user response:

    numlist = [4, 4, 4, 4, 4, 3, 3, 3, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1]
    
    # Method 1
    for index, value in enumerate(numlist):
        if value == 1:
            print(index, value)
    
    counter = 0
    
    # Method 2
    for i in numlist:
        if i == 1:
            print(counter, i)
            
        counter = counter   1

CodePudding user response:

numlist=[4,4,4,4,4,3,3,3,3,2,1,1,1,1,1,1,1,1]


def index(numlist, num):

    checked = []

    for i in range(len(numlist)):

        if num == numlist[i] and i not in checked:

            checked.append(i)

    return checked

print(index(numlist, 4))

This will return a list of indices.

  • Related