0

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

3

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
3
  • 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. Commented 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. cheers Commented Jul 6, 2012 at 13:44
  • @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. Commented Jul 6, 2012 at 13:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.