How to access the previous element of a list in a list of listsin Python?

Take this code for example:

import csv
with open('Airports.txt', 'r') as f:
    reader = csv.reader(f)
    amr_csv = list(reader)
    for line in amr_csv:
        print(line)

For an input of:
JFK,John F Kennedy International,5326,5486.
ORY,Paris-Orly,629,379.
MAD,Adolfo Suarez Madrid-Barajas,1428,1151.
AMS,Amsterdam Schiphol,526,489.
CAI,Cairo International,3779,3584.

The code outputs a list like so: [['JFK', 'John F Kennedy International', '5326', '5486'], ['ORY', 'Paris-Orly', '629', '379'], ['MAD', 'Adolfo Suarez Madrid-Barajas', '1428', '1151'], ['AMS', 'Amsterdam Schiphol', '526', '489'], ['CAI', 'Cairo International', '3779', '3584'], []]

So let's say when the iterator is at the second element and I want to compare its value with an element from the first element, (example: comparing ORY with JFK) what do I do? If I do a:

j = i-1 
for i in line: 
    if i[0] != j[0]

it gives me an error:
j = i-1.
TypeError: unsupported operand type(s) for -: 'list' and 'int'.

How can I do this without an error?


Solution 1:

Given the input:

input = [['JFK', 'John F Kennedy International', '5326', '5486'], ['ORY', 'Paris-Orly', '629', '379'], ['MAD', 'Adolfo Suarez Madrid-Barajas', '1428', '1151'], ['AMS', 'Amsterdam Schiphol', '526', '489'], ['CAI', 'Cairo International', '3779', '3584'], []]

You can iterate the list like this:

for i in range(1, len(input)):
    print(f'{input[i-1][0]}, {input[i][0]}')

This will print:

JFK, ORY
ORY, MAD
MAD, AMS
AMS, CAI

Just use the variable references for your comparison purposes and whatever instructions you need to code based on the equality result.

Solution 2:

I don't know of a "built-in" feature allowing one to get the "prior" item in a list. Getting it via mylist[index -1] is certainly a valid option (see answer by @cesarv: https://stackoverflow.com/a/70685822/218663) that I upvoted.

However, if it was me, I would personally be more explicit about things so that someone in the future was not potentially guessing about what I was attempting to do.

To that end, I would maintain a prior variable.

data_in = [
    ['JFK', 'John F Kennedy International', '5326', '5486'],
    ['ORY', 'Paris-Orly', '629', '379'],
    ['MAD', 'Adolfo Suarez Madrid-Barajas', '1428', '1151'],
    ['AMS', 'Amsterdam Schiphol', '526', '489'],
    ['CAI', 'Cairo International', '3779', '3584'],
]

prior = data_in[0]
for current in data_in[1:]:
    print(f'{prior[0]}, {current[0]}')
    prior = current