user3033194
user3033194

Reputation: 1821

IndexError with list in Python

I have a function which takes 2 arguments - an input string, and a list of words. For every word in the list which is present in the string, the function returns "True", else "False".

My code is given below:

#!/usr/bin/python


# inputStr is a string, inputList is  list of strings

def keyword_usage(inputStr, inputList):

    splitStr = inputStr.split();
    L = [];
    k = 0;
    bool = 0;

    for i in range(0,len(inputList)):

        for  j in range(0, len(inputStr)):

            if inputList[i]==splitStr[j]:
                bool = 1;
            else:
                bool = 0;
        if bool==1:
            L[k] = "True";
        else:
            L[k] = "False";
        k+=1;
    return tuple(L);

I am running it in the interpreter as shown below:

>>> from keyword_usage import keyword_usage
>>> res = keyword_usage('Dive  Into  Python',  ['Python',  'python', 'scala'])

When I press enter, I get this:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "keyword_usage.py", line 17, in keyword_usage
    if inputList[i]==splitStr[j]:
IndexError: list index out of range

I am new to Python coding and am very confused. It seems a basic question, but I could not get any answer on any forum. Can someone spot the error? Thanks in advance!!

Upvotes: 0

Views: 115

Answers (5)

cezar
cezar

Reputation: 12012

And let's take it one step beyond. Learn to know the comprehension lists:

def keyword_usage(inputStr, inputList):
    splitStr = inputStr.split()
    L = [i in splitStr for i in inputList]
    return tuple(L)

Now you can run the function:

keyword_usage('Dive Into Python', ['Python', 'python', 'scala'])
>>> (True, False, False)

But I would extend the function even on step further:

def keyword_usage(inputStr, inputList):
    splitStr = inputStr.split()
    L = [i in splitStr for i in inputList]
    return dict(zip(inputList, L))

Now you have this result:

keyword_usage('Dive Into Python', ['Python', 'python', 'scala'])
>>> {'Python': True, 'python': False, 'scala': False}

So you know immediately which list element was found in the string.

You can rewrite the list comprehension like this:

L = [(i in splitStr) for i in inputList]

for better readability, if you like it more.

The built-in function zip combines two lists together, first element of list A with the first element of list B, second element of list A with the second element of list B, and so on. The built-in function dict then makes a nice dictionary of these values.

Enjoy!

Upvotes: 1

cezar
cezar

Reputation: 12012

I would suggest a more pythonic solution:

def keyword_usage(inputStr, inputList):
    splitStr = inputStr.split()
    L = []
    for i in inputList:
        L.append(i in splitStr)
    return tuple(L)

That's it!

Use the in operator. It checks if an element is present in a list and returns True or False.

'Dive' in ['Python', 'python', 'scala']
>>> False
'Python' in ['Python', 'python', 'scala']
>>> True

Upvotes: 2

Vishnu Upadhyay
Vishnu Upadhyay

Reputation: 5061

print len(splitStr)

gives :- 3

print len(inputList), len(inputStr)

gives:- 3, 18

when you check

if inputList[i]==splitStr[j] #for i = 1 and j = 12

while splitStr just have three values ['Dive', 'Into', 'Python']

when you run for j in range(0, len(inputStr)) it will loop for 18 times anf every time j takes values from (0,18) so it checks for splitStr[j] let's say 10 then splitStr[10] which is actually (['Dive', 'Into', 'Python']) out of range.

Upvotes: 0

Vincent Beltman
Vincent Beltman

Reputation: 2104

Use this:

def keyword_usage(inputStr, inputList):
    splitStr = inputStr.split();
    L = []
    b = False
    for i in range(0,len(inputList)):
        for  j in range(0, len(inputStr)):
            b = inputList[i]==splitStr[j]
        L.append(b)
    return tuple(L)

print keyword_usage('Dive  Into  Python',  ['Python',  'python', 'scala'])

You made a lot of mistakes:

  • Python doesn't use ';'
  • Don't use 0 or 1 as boolean but use True and False instead.
  • Now you can save True or False in that boolean
  • In the seccond loop, I think you ment splitStr instead of inputList

And the error was caused by:

L[k] = "True";

Since L has no items yet, you can't add items that way. Use append instead:

L.append("True")

Ouput now:

(True, False, False)

Upvotes: 1

Nonnib
Nonnib

Reputation: 468

It looks like just a typo.

This:

for  j in range(0, len(inputStr)):

Should be this:

for j in range(0, len(splitStr)):

Upvotes: 0

Related Questions