Skip to content

Commit ee054a1

Browse files
committed
Sample code for the membership operators article
1 parent f10cb57 commit ee054a1

File tree

5 files changed

+56
-0
lines changed

5 files changed

+56
-0
lines changed

python-in-operator/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Python's "in" and "not in" Operators: Check for Membership
2+
3+
This folder provides the code examples for the article [Python's "in" and "not in" Operators: Check for Membership](https://realpython.com/python-in-operator/).

python-in-operator/performance.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from timeit import timeit
2+
3+
a_list = list(range(100_000))
4+
a_set = set(range(100_000))
5+
6+
7+
list_time = timeit("-1 in a_list", number=1, globals=globals())
8+
set_time = timeit("-1 in a_set", number=1, globals=globals())
9+
10+
print(f"Sets are {(list_time / set_time):.2f} times faster than Lists")

python-in-operator/permissions.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class User:
2+
def __init__(self, username, permissions):
3+
self.username = username
4+
self.permissions = permissions
5+
6+
7+
admin = User("admin", "wrx")
8+
john = User("john", "rx")
9+
10+
11+
def has_permission(user, permission):
12+
return permission in user.permissions
13+
14+
15+
has_permission(admin, "w")
16+
has_permission(john, "w")

python-in-operator/stack.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Stack:
2+
def __init__(self):
3+
self.items = []
4+
5+
def push(self, item):
6+
self.items.append(item)
7+
8+
def pop(self):
9+
return self.items.pop()
10+
11+
# def __iter__(self):
12+
# yield from self.items
13+
14+
def __contains__(self, item):
15+
return item in self.items
16+
17+
# def __getitem__(self, index):
18+
# return self.items[index]

python-in-operator/users.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
username = input("Username: ")
2+
password = input("Password: ")
3+
4+
users = [("john", "secret"), ("jane", "secret"), ("linda", "secret")]
5+
6+
if (username, password) in users:
7+
print(f"Hi {username}, you're logged in!")
8+
else:
9+
print("Wrong username or password")

0 commit comments

Comments
 (0)