0

So I'm writing a python code and I want to have a for loop that counts from the the 2nd item(at increment 1). The purpose of that is to compare if there are any elements in the list that match or are included in the first element.

Here's what I've got so far:

            tempStr = list500[0]

            for item in list500(1,len(list500)):
                if(tempStr in item):
                    numWrong = numWrong - 1
                    amount540 = amount540 - 1

However the code doesn't work because the range option doesn't work for lists. Is there a way to use range for a list in a for loop?

2 Answers2

2

You can get a subset of the list with the code below.

        tempStr = list500[0]

        for item in list500[1:]:
            if(tempStr in item):
                numWrong = numWrong - 1
                amount540 = amount540 - 1

The [1:] tells Python to use all elements of the array except for the first element. This answer has more information on list slicing.

Community
  • 1
  • 1
Adam
  • 4,445
  • 1
  • 31
  • 49
1

Use a function:

search_linear(mainValues, target)

This is the algorithm you are looking for: http://en.wikipedia.org/wiki/Linear_search

All you need to do is set the starting point equal to +1 in order to skip your first index, and than use array[0] to call your first index as the target value.

def search_linear(MainValues, Target):
    result = []
    for w in Target:
        if (search_linear(MainValues, w) < 0):
            result.append(w)
    return result
Andrew
  • 995
  • 6
  • 10