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

Why is the printing order reversed in a simple loop built inside a function(Python)

I have a simple function inside which i run a loop and then perform split operation on the extracted string element. Once operation is done on the current element i am printing the 2nd splitted text of the complete string and then moving to next element of the list.

However, when the function is called, i find the output printed in reverse order i.e. from the last element of list to first.

Here is the code:

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

s={"i am good", " i am fine"}
def splitter():
    for i in s:
        print(i.split()[2])
splitter()

Output:

fine
good

However, expected output is:

good
fine

>Solution :

Because sets are not ordered in python, you can use list instead

s = ["i am good", " i am fine"]
def splitter():
    for i in s:
        print(i.split()[2])
splitter()
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