Problem Formulation
- Given a list of lists
lst
, and - Given an element
x
.
How to find the row and column index of the element x in the list of lists lst
?
If the element does not occur in a list, the return value should be the tuple (-1, -1)
. If the element exists multiple times, the return value should be the (row, column)
index of the first occurrence.
Here are three examples that demonstrate how your program should work under three important cases.
Example 1: Element Exists
Input: [[1, 2, 3], [4, 5, 6]] x = 5 Output: (1, 1)
Example 2: Element Doesn’t Exist
Input: [[1, 2, 3], [4, 5, 6]] x = 0 Output: (-1, -1)
Example 3: Element Exists Multiple Times
Input: [['Alice', 'Bob'], ['Carl', 'Dave', 'Emil'], ['Emil', 'Emil']] x = 'Emil' Output: [1, 3]
Let’s dive into the solutions next!
Method 1: Basic Python For Loop & enumerate()
The simplest and most Pythonic way that finds the row and column indices in a general list of lists, is to use a nested for loop and the built-in enumerate()
function to iterate over the elements and indices at the same time.
Here’s the code solution:
def find_element(x, lst): for i, row in enumerate(lst): for j, element in enumerate(row): if element == x: return (i, j) return (-1, -1)
- The outer for loop iterates over the inner lists and their “row” indices using
enumerate()
. If you need a refresher on enumerate, check out my in-depth tutorial on the Finxter blog and watch the explainer video at the end of this section. - The inner loop iterates over each element in a given inner list, along with its “column” index.
- As soon as you’ve found the element, return the tuple of the row and column indices
(i, j)
.
Let’s run our three test cases against it!
# Test Case 1: Element Exists lst = [[1, 2, 3], [4, 5, 6]] x = 5 print(find_element(x, lst)) # Test Case 2: Element Doesn't Exist lst = [[1, 2, 3], [4, 5, 6]] x = 0 print(find_element(x, lst)) # Test Case 3: Element Exists Multiple Times lst = [['Alice', 'Bob'], ['Carl', 'Dave', 'Emil'], ['Emil', 'Emil']] x = 'Emil' print(find_element(x, lst))
The output is the expected:
(1, 1) (-1, -1) (1, 2)
Before we dive into the next solution, feel free to find an in-depth explanation of the enumerate()
function here:
Method 2: enumerate() and list.index()
An alternative way to accomplish the same task is as follows.
To find the (row, column)
index pair of an element in a list of lists, iterate over the rows and their indices using the enumerate()
function and use the row.index(x)
method to determine the index of element x
in the row
.
A bit of additional code is needed to make sure that if the element is not found in a given row, the raised Error is properly handled:
def find_element(x, lst): for i, row in enumerate(lst): try: return (i, row.index(x)) except: pass return (-1, -1)
The try/except code block handles the cases where the element doesn’t exist in the row. Alternatively, you could use a simple check like so:
def find_element(x, lst): for i, row in enumerate(lst): if x in row: return (i, row.index(x)) return (-1, -1)
This is more readable and more concise but it does a bit of additional work: if the element does exist, it searches it twice in the list, once for the membership operation and once for the row.index(x)
method.
Method 3: A One-Liner Solution
if you enjoy Python one-liners like I do, you’ll love this one:
find_element = lambda x, lst: [(i, row.index(x)) for i, row in enumerate(lst) if x in row]
- You create a variable
find_element
and assign a dynamic function object to it, created using thelambda
keyword. - The function takes two arguments
x
andlst
. The first is the element to be searched in the list of listslst
. - It returns a list of all found occurrences using a list comprehension statement. If you need a refresher on list comprehension, check out my detailed guide on the Finxter blog and watch the explainer video at the end of this section.
- In the list comprehension statement, we iterate over all rows and their indices and use the
row.index(x)
method to check the index of the first occurrence ofx
inrow
if it exists.
Note that the output is now a list of tuples—each representing one found occurrence. However, if you strictly need the formatting requirements defined in the problem formulation, you can slightly modify it like so:
def find_element(x, lst): res = [(i, row.index(x)) for i, row in enumerate(lst) if x in row] return res[0] if res else (-1, -1)
Here’s the promised explainer on list comprehension—a critical Python feature:
π Recommended Tutorial: How to Access Elements From a List of Tuples
In case you haven’t already, check out my book Python One-Liners which contains my condensed knowledge on how to write concise and effective Python code in a single line! It’s fun to build your one-liner superpower!!
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.