Oct-09-2021, 02:52 PM
In my opinion, the list-comprehension is the cleanest solution.
If you have many conditions to fulfill, you can create a function which does the job for you.
If you have many conditions to fulfill, you can create a function which does the job for you.
def even(user): """ True if uid is even This function could check more. Just a silly example """ return user["uid"] % 2 == 0 # already existing data data = [{"uid": num, "name": f"user_{num}"} for num in range(1, 101)] # later the new list is assigned to the name data data = [user for user in data if even(user)]If you work inside a function and want to assign the new list, this will need the use of
global
, if the list is defined outside the function. This is not very nice. A class can solve this problem of reassigning without the use of global
.class Something: def __init__(self): self.database = [{"uid": num, "name": f"user_{num}"} for num in range(1, 101)] def add_user(self, uid, name): self.database.append({"uid": uid, "name": name}) def delete_odd_users(self): self.database = [user for user in self.database if self.is_even(user)] def is_even(self, user): return user["uid"] % 2 == 0If you're using threads, you should better use locking to prevent race conditions.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!