Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first position of values in list

Tags:

python

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

like image 520
Mat.S Avatar asked Jun 22 '17 02:06

Mat.S


People also ask

How do you find the first instance of a value in a list?

To find index of the first occurrence of an element in a given Python List, you can use index() method of List class with the element passed as argument. The index() method returns an integer that represents the index of first match of specified element in the List.

How do you find the position of an item in a list in Python?

To find an element in the list, use the Python list index() method, The index() is an inbuilt Python method that searches for an item in the list and returns its index. The index() method finds the given element in the list and returns its position.

How do I find the first instance of a value in Python?

Use the find() Function to Find First Occurrence in Python We can use the find() function in Python to find the first occurrence of a substring inside a string. The find() function takes the substring as an input parameter and returns the first starting index of the substring inside the main string.

What is the starting index position in list?

The list index starts with 0 in Python. So, the index value of 1 is 0, 'two' is 1 and 3 is 2.


1 Answers

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)
like image 66
student Avatar answered Oct 01 '22 20:10

student