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]
##############
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
Sven Marnach
608k123 gold badges969 silver badges866 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
JensD
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
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. cheers
Sven Marnach
@JensD: A slicing
a[i:j] returns a sublist of length j - i. If this difference is one, you get a sublist of length 1. It would be inconsistent if you would get the item itself.lang-py