Return the Index at Which an Element Is First Found in a List - Python

I need to write a function ind(e, L), which takes in a list L and an element e. The function ind() should return the index at which e is first found in L. Counting begins at 0. If e is not an element of L, then ind(e, L) should return the integer equal to len(L).

This is what I have so far:

def ind(e, L):
    if e in L:
        return [L].index('e')
    if e not in L: 
        return len[L]

Can someone help me please because I can't figure it out!

1

4 Answers

You need to do some changes.

  • remove square brackets which exists around L.
  • remove the quotes which exists around e, since e is a variable not value.
  • Add try, except block.

Code:

>>> def ind(e, L):
        try: 
            return L.index(e) 
        except ValueError: 
            return len(L)


>>> ind(3, [1,2])
2
>>> ind(3, [1,2,3,4,3])
2
>>> ind('r', ['a'])
1
>>> ind('r', ['a', 'r'])
1
>>> 
4

In addition to @Avinash's answer, I suggest using a tenary conditional operator to be a bit brief:

In [25]: def ind(e, L):
    ...:     return L.index(e) if e in L else len(L)

In [26]: lst=[1,2]

In [27]: ind(2, lst)
Out[27]: 1

In [28]: ind(33, lst)
Out[28]: 2

Or try what @vaultah commented:

In [43]: def ind2(e, L):
    ...:     try: 
    ...:         return L.index(e) 
    ...:     except ValueError: 
    ...:         return len(L)
    ...:     

To benchmark:

In [65]: s='Python is a dynamic and strongly typed programming language that is designed to emphasize usability. Two similar but incompatible versions of Python are in widespread use (2 and 3). Please consider using [python-2.7] or [python-3.x] tags for version-specific questions about Python.'

In [66]: lst=list(s)

In [67]: %timeit ind('r', lst)
The slowest run took 6.81 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 989 ns per loop

In [68]: %timeit ind2('r', lst)
The slowest run took 5.01 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 640 ns per loop

In [69]: lst2=list(s.replace('r', '')) #remove all 'r's in the list

In [70]: %timeit ind('r', lst2)
100000 loops, best of 3: 3.77 µs per loop

In [71]: %timeit ind2('r', lst2)
The slowest run took 4.12 times longer than the fastest. This could mean that an intermediate result is being cached 
100000 loops, best of 3: 5.61 µs per loop

In [72]:

Note that the try-except logic is not always more efficient

Or, without introducing exception handling or calling out to Python's own list.index method:

def ind(e, L):
    for index, item in enumerate(L):
        if item == e:
             return index

    return index+1

This code should work:

def ind(e, L):
    if e in L:
        return L.index(e)
    if e not in L: 
        return len (L)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest