GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Books
  • Mini
  • Tips
  • Tags
  • About
  • learnbyexample
  • Python tip 2: membership operator

This view

  • Original page
  • New address

GeezerVison is showing learnbyexample.github.io — Python tip 2: membership operator

The in membership operator checks if a given value is part of a collection of values. Here's an example with range() function:

>>> num = 5

# checks if num is present among the integers 3 or 4 or 5
>>> num in range(3, 6)
True

Instead of a series of == comparisons combined with the or boolean operator, you can utilize the in operator.

>>> pet = 'cat'

# instead of doing this
>>> pet == 'bat' or pet == 'cat' or pet == 'dog'
True

# use the membership operator
>>> pet in ('bat', 'cat', 'dog')
True

When applied to strings, the in operator performs substring comparison.

>>> fruit = 'mango'

>>> 'an' in fruit
True
>>> 'at' in fruit
False

To invert the membership test, use the not in operator.

>>> pet = 'parrot'

>>> pet in ('bat', 'cat', 'dog')
False
>>> pet not in ('bat', 'cat', 'dog')
True

Video demo:


info See docs.python: Membership test operations for documentation. See also my 100 Page Python Intro ebook.

#python#tip

← Python tip 3: expression and result with f-string

Python tip 1: tuple argument for startswith/endswith methods →


📰 Use this link for the Atom feed.
✅ Follow me on Twitter, GitHub and Youtube for interesting tech nuggets.


You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.