Q:

Python-search function

I want to write a search function that takes in a value x and a sorted sequence and returns the position that the value should go to by iterating through the elements of the sequence starting from the first element. The position that x should go to in the list should be the first position such that it will be less than or equal to the next element in the list.
 Example:>>> search(-5, (1, 5, 10))——0
         >>> search(3, (1, 5, 10))——1

A:

Building a list of every item would be a bit of a waste of resources if there were big gaps in the list, instead you can just iterate through each list item until the input is bigger than the value.
In terms of your code -
def search(input,inputList):
    for i in range( len( inputList ) ):
        if inputList[i]>input:
            return i
    return len( inputList )

print search(-5, (1, 5, 10))
#Result: 0
print search(3, (1, 5, 10))
#Result: 1

To insert it into the list, this would work, I split the list in 2 based on the index and add the value in the middle.
def insert(input,inputList):
    index = search(input,inputList)                    #Get where the value should be inserted
    newInput = [input]+list(inputList[index:])         #Add the end of the list to the input
    if index:
        newInput = list(inputList[:index])+newInput    #Add the start of the list if the index isn't 0
    return newInput

print insert(-5, (1, 5, 10))
#Result: (-5, 1, 5, 10)
print insert(3, (1, 5, 10))
#Result: (1, 3, 5, 10)

