Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare list items

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 !

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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]}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading