Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python get index of first element of list that matches condition

# Find first index (or value) that meets condition
my_list = [2, 4, 6, 9, 10]

# Option 1. Use an iterator (does not scan all list)
y = (i for i,x in enumerate(my_list) if is_odd(x))
idx1 = next(y)  # <== index of first element

y = (x for i,x in enumerate(my_list) if is_odd(x))
v1 = next(y)  # <== value of first element


# Option 2. Use a list comprehension (scans all list)
idx1 = [i for i,x in enumerate(my_list) if x % 2 != 0][0]
v1 = [x for i,x in enumerate(my_list) if x % 2 != 0][0]
Comment

python find index of first matching element in a list

# Basic syntax:
list.index(element, start, end) 
# Where:
#	- Element is the item you're looking for in the list
# 	- Start is optional, and is the list index you want to start at
#	- End is optional, and is the list index you want to stop searching at

# Note, Python is 0-indexed

# Example usage:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 42, 9, 10]
my_list.index(42)
--> 8
Comment

PREVIOUS NEXT
Code Example
Python :: showing specific columns pandas 
Python :: current date and time django template 
Python :: int to ascii python 
Python :: asymmetric encryption python 
Python :: np.random.RandomState 
Python :: how to map longitude and latitude in python 
Python :: how to access dataframe row by datetime index 
Python :: how to make a list a string 
Python :: exclude last value of an array python 
Python :: python zip folder 
Python :: python isinstance list 
Python :: mid point formula 
Python :: c++ vs python 
Python :: max in a list python 
Python :: install a lower version of python using conda 
Python :: how to add textbox in pygame window 
Python :: raspberry pi keyboard python input 
Python :: correlation with specific columns 
Python :: django tempalte tag datetime to timestamp 
Python :: how to search in django 
Python :: kivy button disable 
Python :: MAKE A SPHERE IN PYTHON 
Python :: .launch.py file in ros2 
Python :: flask wtforms multiple select 
Python :: add two numbers in python 
Python :: random 2 n program in python 
Python :: calculate days between two dates using python 
Python :: Returns the first n rows 
Python :: django form list option 
Python :: matplotlib set integer ticks 
ADD CONTENT
Topic
Content
Source link
Name
3+9 =