'Most pythonic way to construct an object not in a container?
Consider a list, or more generally a container C, that contains different hashable objects of different types.
I would like to construct an hashable object that is not in C in a efficient and pythonic way.
Currently, I do the following:
i = 0
while i in C: # while i is in the container C
i += 1
# at the end of the loop, i is not in C
However, it feels very inefficient and not very pythonic...
So my question is: given a container that contains different hashable objects, what is the best way to construct an hashable object that is not in this container?
(For context, I am doing some graph theory and I need to add to my graph a temporary and artificial node that I shall remove later.)
Solution 1:[1]
Your approach can be simplified by using Graph.__len__:
G.add_node(len(G))
Note however that this approach works only if you know a priori that your graph only contains nodes 0 .. len(G) - 1.
To solve the general problem of finding an object that is not in the container, I would create a new class from scratch. Here is an example:
container = ['A', 3, None, 3.0, True]
class MyClass:
_hash_val = max([hash(x) for x in container]) + 1
def __hash__(self):
return MyClass._hash_val
def __eq__(self, other):
return isinstance(other, MyClass)
container.append(MyClass())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
