Home > OS >  How to compare list items
How to compare list items

Time:11-23

I have a list with few items and I need to compare Consecutive items of them.

e.g:

     'item_1' 'item_2'
     'item_2' 'item_3'
     'item_3', 'item_4'
     'item_4', 'item_5'
     'item_5', 'item_6'
     'item_6', 'item_7'

I tried with some coding part like this. But it unsuccessfully !

my_list = ['item_1', 'item_2', 'item_3', 'item_4', 'item_5', 'item_6', 'item_7']

for (a, b) in zip(my_list [0::2], my_list [1::2]):
    print(f"{a} {b}")

Please help me to get the result accurately.

CodePudding user response:

You almost had it - try

for (a, b) in zip(my_list[1:], my_list[:-1]):
    print(f"{a} {b}")

IMO this is also one of the occasions where you could be forgiven for using indexes to access list elements:

for i in range(len(my_list) - 1):
            print(f"{my_list[i 1]} {my_list[i]}")
  • Related