1

Hello I am trying to add numbers to a new list in a for loop if condintions match. However I do not get the result I was hopping for. For me it seems like the for loop stops after the first encounter of a match ever though i is probably analized.

print(months_list)

for i in months_list:
    n_days_list = []
    if i == 1 or 3 or 5 or 7 or 8 or 10 or 12:
        n_days_list.append(31)
    elif i == 2:
        n_days_list.append(28)
    else:
        n_days_list.append(30)

print(n_days_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

[31]

Thanks for the help.

Kuehlschrank
  • 109
  • 6
  • This might already be answered somewhere else but the linked answer is not correct. Your issue is that you make a new list inside of your loop so you run through all the values but you are left with only the last one at the end. – David Oldford Nov 15 '20 at 14:31

1 Answers1

0

The reason why the length of ur code's output is 1 is because you are initializing the n_days_list to [] at each iteration which means u are removing the effect of the previous iteration. However, if u remove "n_days_list = []", you will end up with a list of length of n_days_list containing only 31 that's bcz the first condition is always true because if i == 1 or 3 or 5 or.... is equivalent to if i == 1 or True or True or.... since the numbers 3, 5.... are different than 0 hence they are True. So just change to if i == 1 or i == 3 or i == 5 or.... and remove that n_days_list = [] and u will be set to go.