HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Finding an element in a list

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
listelementfinding

Problem

I'm kind of new to Python. So, I wonder which method is better to use in a function to find an element in a list.

First:

def search_binary(xs,target):
    count = 0
    for i in xs:
        if i == target:
            return count
            count = count +1
        else:
            count = count +1
            continue
    return -1


Second:

def search_binary(xs, target):
    lb = 0
    ub = len(xs)
    while True:
        if lb == ub:   
           return -1

        mid_index = (lb + ub) // 2

        item_at_mid = xs[mid_index]

        if item_at_mid == target:
            return mid_index      
        if item_at_mid < target:
            lb = mid_index + 1    
        else:
            ub = mid_index

Solution

If your list is sorted you can use binary search (your second code), and it will be faster for large lists, but if it's unsorted you'll have to keep to linear search. The Python library provides fast implementation of both methods, so you really don't need to roll your own:

>>> a = range(10)

>>> a.index(4) # linear search
4

>>> import bisect
>>> idx = bisect.bisect(a, 4) # binary search
>>> if a[idx-1] == 4:
...     print idx - 1
... else:
...     raise ValueError('item not in list')
... 
4

Code Snippets

>>> a = range(10)

>>> a.index(4) # linear search
4

>>> import bisect
>>> idx = bisect.bisect(a, 4) # binary search
>>> if a[idx-1] == 4:
...     print idx - 1
... else:
...     raise ValueError('item not in list')
... 
4

Context

StackExchange Code Review Q#39329, answer score: 5

Revisions (0)

No revisions yet.