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)
.
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.
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.
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.
The list index starts with 0 in Python. So, the index value of 1 is 0, 'two' is 1 and 3 is 2.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With