How to check if the element is contained in list or not?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jimmy45
    New Member
    • Apr 2010
    • 8

    How to check if the element is contained in list or not?

    Hello,

    I have some problem with checking if the element is contained in the list or not.

    For example:
    a = ['abc', 'def', 'gh', 'i']
    b = 'abc'

    Following is my code:
    Code:
    def is_proper_word(b, a) :
    
        is_proper = False
        for b in proper_word_list:
            is_proper = True
        return is_proper
    Is it correct?

    Thank you in advance.
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Hi

    With a and b as you suggest
    Code:
    b in a
    returns True.

    It seems unnecessary to do more work than this single line, but if you have a reason post back.

    Actually post back anyway to let us know how it goes.

    Comment

    • Glenton
      Recognized Expert Contributor
      • Nov 2008
      • 391

      #3
      By the way, your code would not work. It would simply create a loop of all the variables in proper_word_lis t, (which isn't defined anyway), calling the items in the list variable b. It would just over-write the b variable that you input.

      Comment

      • Nonemsludo
        New Member
        • Apr 2010
        • 15

        #4
        Originally posted by Jimmy45
        Hello,

        I have some problem with checking if the element is contained in the list or not.

        For example:
        a = ['abc', 'def', 'gh', 'i']
        b = 'abc'

        Following is my code:
        Code:
        def is_proper_word(b, a) :
        
            is_proper = False
            for b in proper_word_list:
                is_proper = True
            return is_proper
        Is it correct?

        Thank you in advance.
        You could use list comprehension,
        [elem for elem in a if elem == b]

        Comment

        • Glenton
          Recognized Expert Contributor
          • Nov 2008
          • 391

          #5
          Oh, if you're wanting to do it that way, you could use numpy arrays with a in b giving a boolean numpy array. Depends what you want to do really.

          Comment

          Working...