mercredi 27 décembre 2017

Consecutive if statements: order of execution

Here is my Python code:

my_constant = 5
my_constant_2 = 6
list_of_lists = [[3,2],[4,7]]

my_new_list = []

for i in list_of_lists:
    my_dict = {}
    for j in i:    
        if j > my_constant:
            my_dict["a"] = "Hello"
            my_dict["b"] = "Hello"
            print(my_dict)
            my_new_list.append(my_dict)
        if j > my_constant_2:
            my_dict["a"] = "Hello"
            my_dict["b"] = "Bye"
            print(my_dict)
            my_new_list.append(my_dict)


print(my_new_list)

Here are the results:

{'a': 'Hello', 'b': 'Hello'}
{'a': 'Hello', 'b': 'Bye'}
[{'a': 'Hello', 'b': 'Bye'}, {'a': 'Hello', 'b': 'Bye'}]

The first two lines of the results are according to my expectations, but the third line is not. I would expect this:

[{'a': 'Hello', 'b': 'Hello'}, {'a': 'Hello', 'b': 'Bye'}]

So it looks that when the loop waits for the second "if" before appending to my_new_list, and us such the my_new_list get twice the new my_dict.

I know that the below code solves the issue (ie moving the my_dict inside the "if"):

my_constant = 5
my_constant_2 = 6
list_of_lists = [[3,2],[4,7]]

my_new_list = []

for i in list_of_lists:
    for j in i:        
        if j > my_constant:
            my_dict = {}
            my_dict["a"] = "Hello"
            my_dict["b"] = "Hello"
            print(my_dict)
            my_new_list.append(my_dict)
        if j > my_constant_2:
            my_dict = {}
            my_dict["a"] = "Hello"
            my_dict["b"] = "Bye"
            print(my_dict)
            my_new_list.append(my_dict)


print(my_new_list)

However, in practice my_dict is not empty and a function is used to create it (and it takes some time). Also, there are more "ifs", so i prefer not to use the above code.

Is there a trick to get over it?

Thanks.

Aucun commentaire:

Enregistrer un commentaire