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 :: maping value to data in pandas dataframe 
Python :: generic python 
Python :: How to install XGBoost package in python on Windows 
Python :: stack overflow python timedate 
Python :: converting month number to month name python 
Python :: pygame how to get surface lenght 
Python :: pandas save one row 
Python :: how to take unknown number of inputs in python 
Python :: euclidean division in python 
Python :: pandas concatenate 
Python :: reverse python dict 
Python :: python one line if else 
Python :: making a function wait in python 
Python :: phone number regex python 
Python :: declare numpy zeros matrix python 
Python :: python string to array 
Python :: python transpose list of lists 
Python :: kaggle vs colab 
Python :: clearing canvas tkinter 
Python :: descending python dataframe df 
Python :: how to add color to python text 
Python :: adding columns in cpecific position 
Python :: python permutation 
Python :: ternary operator python 
Python :: python3 change file permissions 
Python :: get list file in folder python 
Python :: python ftp login 
Python :: shutil copyfile python 
Python :: ImportError: No module named flask 
Python :: isidentifier method in python 
ADD CONTENT
Topic
Content
Source link
Name
2+5 =