Conditional statement with or without else

Hello guys,

I hope you are well.

I have question about the if statement. Indeed I don’t understand why the outputs of the codes below are not identical :

Code 1 :

android_clean = []
already_added = []

for app in googleplay[1:] :
    name = app[0]
    n_reviews = float(app[3])
    if (reviews_max[name] == n_reviews) and (name not in already_added):
        android_clean.append(app)
    else: already_added.append(name)

print(len(android_clean))

print(len(android_clean)) = 9664

Code 2 :

android_clean = []
already_added = []

for app in googleplay[1:] :
    name = app[0]
    n_reviews = float(app[3])
    if (reviews_max[name] == n_reviews) and (name not in already_added):
        android_clean.append(app)
        already_added.append(name)

print(len(android_clean))

print(len(android_clean) = 9659

Many thanks for your help,

Think about what if-else does and consider a small example for it -

list1 = [1, 4]
list2 = [1, 2, 3, 4]
list3 = []
list4 = []

for i in list2:
    if i in list1:
        list3.append(i)
        list4.append(i)

and the other case -

list1 = [1, 4]
list2 = [1, 2, 3, 4]
list3 = []
list4 = []

for i in list2:
    if i in list1:
        list3.append(i)
    else:
        list4.append(i)
  • Think through the code above.
  • Think what would list3 and list4 contain if you print those out at the end for the first code
  • Think what would list3 and list4 contain if you print those out at the end for the second code.
    • I would recommend instead of typing out the code or copying it and running it to see the result, work through it on pen and paper.
  • Compare the above two
  • Think about the project code based on the above

If you get stuck at any point in the process above, feel free to ask questions based on where you get stuck.

Hello @the_doctor,

Thank you very much for your response, it helps me to understand ! :blush:

Glad I could help. If you think the answer could be helpful to other learners in the community then please consider marking it as a solution.