I am very new to programming and I am trying to practice lists and for loops. I am trying to take one item from a list and append/extend it to a new list if it meets the condition Some of the elements of the lists, clearly don't meet the condition but somehow they end up in my output. What am I doing wrong? Thank you for taking the time to answer
hours=[12, 5, 6, 4.6, 3]
a=[]
for i in hours:
if i % 2==0 :
a.extend(hours)
del hours [:]
print(a)
CodePudding user response:
First of all - to add a single element to a
, you should use append
instead of extend
- such as a.append(hours)
. Secondly, the element of hours
which you presumably want to put in a
is i
, not the whole hours
list - so just write a.append(i)
.
I'm not sure what the del
statement is doing there - do you want to remove i
from hours? If so, use hours.remove(i)
(though there are probably faster ways to do this).
CodePudding user response:
hours=[12, 5, 6, 4.6, 3]
a=[]
for i in hours:
if i % 2==0 :
a.append(i)
print(a)
Output:
[12, 6]
CodePudding user response:
The problem in your code is this del. When you remove from your main list "hours", then the loop change. If you only want to append in other list, dont remove from the main one.
CodePudding user response:
so what i see is that you are trying to append a number into the list a if he is even, i don't know why you are clearing the hours list, because the for loop then stops. By the what works for me is:
hours=[12, 5, 6, 4.6, 3]
a=[]
for i in hours:
if i % 2==0 :
a.append(i)
print(a)