Mat.S
Mat.S

Reputation: 1854

Find first position of values in list

If I have a list of 1's and 2's, how can I find the first index of 1 and 2.

For example [1,1,1] should output (0,-1), where -1 represents not in the list and [1,2,1] should output (0,1), [1,1,1,2] should output (0,3).

Upvotes: 5

Views: 3150

Answers (1)

niraj
niraj

Reputation: 18208

One way would be to create a separate list for items to look index for and use index function and using list comprehension (also additional check is made to make sure item is in list else ValueError will occur):

my_list = [1,1,1]
items = [1,2]
print ([my_list.index(item) if item in my_list  else -1 for item in items])

Output:

[0, -1]

If tuple is needed then the above list can be converted into tuple using tuple function:

tuple([my_list.index(item) if item in my_list else -1 for item in items])

In longer way without using list comprehension:

my_list = [1,1,1]
items = [1,2]
# create empty list to store indices
indices = []

# iterate over each element of items to check index for
for item in items:
    # if item is in list get index and add to indices list
    if item in my_list:
        item_index = my_list.index(item)
        indices.append(item_index)
    # else item is not present in list then -1 
    else:
        indices.append(-1)

print(indices)

Upvotes: 10

Related Questions