what am i doing wrong with my if statement that it doesn't recognise if an element in a is equal to 0? what i am attempting to print is for ever 0 the program prints .
and for ever 1 #
. cheers.
a=[0,0,1,0,1,1,0,1,1,0,0,0,0,1]
print(a)
for i in range(len(a)):
if a[i]==[0]:
print('.', end='')
else:
print('#', end='')
print()
bash:
[0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1]
##############
asked Jul 6, 2012 at 13:12
1 Answer 1
You probably want
if a[i] == 0:
instead of
if a[i] == [0]:
You want to compare the items to the integer value 0
, not to the single-element list [0]
.
answered Jul 6, 2012 at 13:13
-
oh yes, thankyou. before when i kept on testing i kept getting not iterable. Im new to programing so its hard to remember what i trying before.JensD– JensD07/06/2012 13:18:15Commented Jul 6, 2012 at 13:18
-
this raises a rhetorical question. why does a[1] return an integer while a[1:2] return a list. i suppose it doesnt matter why, but its interesting to note and the reason for my confusion. cheersJensD– JensD07/06/2012 13:44:21Commented Jul 6, 2012 at 13:44
-
@JensD: A slicing
a[i:j]
returns a sublist of lengthj - i
. If this difference is one, you get a sublist of length 1. It would be inconsistent if you would get the item itself.Sven Marnach– Sven Marnach07/06/2012 13:48:07Commented Jul 6, 2012 at 13:48
lang-py