List isnt getting appended with contents of another list in Python

Question:

I’m attempting to find specific sections of a list that was pulled from a csv file. using 2 different functions. I don’t know what the issue is but the return value is blank.

def find_flight(filename, airlines, city, earliest, latest):
    mf = []
    lf = []
    mf = get_filtered_CSV(filename, airlines)
    for row in mf:
        if mf[1] == city:
            if latest > mf[2] >= earliest:
                lf.append(row)
            else:
                pass
        else:
            pass
    return lf

//

def get_filtered_CSV(filename, filter_by):
    lst = []
    with open(filename, 'r') as myfile:
        csv_reader = csv.reader(myfile)
        for row in csv_reader:
            if row[0] == filter_by:
                lst.append(row)
    return lst

print(find_flight("Airport.csv", "United", "Portland", "0000", "2400"))
Asked By: TiTanTeThaR

||

Answers:

Try removing the index as 0 because it might be considering 0^th index of the string.
In the function get_filtered_CSV

update if row[0] == filter_by:
to if row == filter_by:

Answered By: Aman Sharma

In find_flight, your loop never uses the row iteration variable except to append it if the other tests pass. All your tests are based on mf (the list of lists you’re iterating over), which does not change from loop to loop. So instead of comparing specific scalar values from each row to other scalar values (str), you’re comparing the second row as a whole (the entire list) to a single scalar value (city, a str) and making a similar mistake comparing the third row as a whole to earliest and latest. Those uses of mf (the outer list) should in fact refer to row (the list for that particular row of data), replacing:

for row in mf:
    if mf[1] == city:
        if latest > mf[2] >= earliest:
            lf.append(row)
        else:
            pass
    else:
        pass

with (also removing the pointless else: passes that serve no purpose):

for row in mf:
    if row[1] == city:  # row[1], not mf[1]
        if latest > row[2] >= earliest:  # row[2], not mf[2]
            lf.append(row)

or combining the tests into one if:

for row in mf:
    if row[1] == city and latest > row[2] >= earliest:
        lf.append(row)

The reason this was silently appending nothing is the mf[1] == city test; mf[1] is a sub-list, and you’re comparing it to a str, and that comparison will always be False. If the code had reached the latest > mf[2] >= earliest test, you’d’ve gotten a TypeError (because a failure to implement > or >= raises TypeError rather than silently returning True or False), but the first test prevents you from getting that far.

Answered By: ShadowRanger
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.