Find the first position of values ​​in a list

If I have list 1 and 2, how can I find the first index 1 and 2.

For example, [1,1,1]

should output (0,-1)

, where -1 is not displayed in the list, but [1,2,1]

should output (0,1)

, [1,1,1,2]

should output (0,3)

.

+3


source to share


1 answer


One way would be to create a separate list of items to watch index

for and use the function index

and use list comprehension

(an additional check is also done to make sure the item is in the else list ValueError

)):

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 a tuple is needed, the above list can be converted to a tuple using the function tuple

:

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

      

Longer 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)

      

+7


source







All Articles