0
list=[1,3,0,3,0,3,0,3,0,3,0,3,0,3,0,3,0,3,0,3,0,3,0,3,1,0,1,3,0,3,0,3,1]

so now i want to know if the 5th object in this list is 3:

if list.index(3)==5:
  print("yes")
else:
  print("no")

-> answer is "no"... but it is, as you see. So how can i solve it?

5
  • I'm not familiar with python 3, but I have to feel that else: no is not valid. Commented Mar 6, 2013 at 14:28
  • @Hoopdady -- That depends on whether no is in the local namespace :P -- e.g. if no = "Hello World" before getting here, it would work on python2 or python3 Commented Mar 6, 2013 at 14:29
  • @mglison -- fair.... I guess I should have said useful instead of valid Commented Mar 6, 2013 at 14:30
  • " i want to know if the 5th object in this list is 3" : print list[5-1]==3 and the mass is over. The -1 is due to the fact that first element is indexed 0. Commented Mar 6, 2013 at 15:07
  • If you absolutely want to print YES or NO : print ('NO','YES')[list[4]==3]. Or print 'YES' if list[4]==3 else 'NO' Commented Mar 6, 2013 at 15:10

1 Answer 1

5
  1. don't use list as a variable name. It masks one very useful command.

  2. index is a list's method returning the position of a given element within a list. You want the opposite: get the element for a given position.

This code will help you. It checks whether the 5th (position 4) element of a list is 3:

lst = [1,3,0,3,0,3,0,3,0,3,0,3,0,3,0,3,0,3,0,3,0,3,0,3,1,0,1,3,0,3,0,3,1]
if lst[4] == 3:
    print('yes')

Your code list.index(3) returns 1, because the first occurence of 3 is at the position 1.

Sign up to request clarification or add additional context in comments.

1 Comment

I think you mean if lst[4] == 3

Your Answer

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.