Skip to content
Advertisement

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

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:

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

Advertisement

Answer

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()
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement